Lesson

MySQL LOG() Function

10 min reading
Free Course

MySQL LOG() Function: Natural and Custom-Base Logarithms

The LOG() function computes either a natural logarithm (base e) or a custom-base logarithm depending on how many arguments you supply. With one argument LOG(x), it matches LN(x) exactly.

With two arguments LOG(b, x), MySQL computes the logarithm of x to base b (LN(x) / LN(b)). That flexibility makes LOG() useful for scoring algorithms, custom scale bucketing, and growth-period calculations.

Syntax

LOG(x)
LOG(base, x)
  • x: Numeric expression strictly greater than 0.
  • base: Optional base value strictly greater than 1.

Practical Example

Suppose demo_products tracks monthly sales volume (units_sold) across fast-moving and slow-moving SKUs. You can compute both the natural log and a base-5 tier score in one report.

SELECT
    product_id,
    product_name,
    units_sold,
    ROUND(LOG(units_sold), 4) AS natural_log,
    ROUND(LOG(5, units_sold), 2) AS base5_score
FROM demo_products
WHERE product_id BETWEEN 101 AND 104;
product_id product_name units_sold natural_log base5_score
101 Mechanical Pencil 125 4.8283 3.00
102 Notebook Pack 25 3.2189 2.00
103 Eraser Set 0 NULL NULL
104 Desk Mat NULL NULL NULL

For 125 units, LOG(5, 125) returns 3.00 because 5^3 = 125. Row 103 has 0 units sold, so both calls return NULL.

Common Mistakes & NULL Behavior

  • Reversing base and value: MySQL puts the base first: LOG(2, 8) returns 3, whereas LOG(8, 2) returns 0.3333. Some languages reverse this order, so double-check your argument positions.
  • Invalid base returns NULL: In MySQL, LOG(b, x) requires b > 1 and x > 0. Passing b <= 1 (such as LOG(1, 10), LOG(0.5, 4), or LOG(0, 10)) returns NULL.
  • Zero or negative x: LOG(0) and LOG(-10) return NULL rather than raising a runtime error.
  • Assuming LOG(100) is base 10: Single-argument LOG(100) uses base e (4.6052), NOT base 10. Use LOG10(100) or LOG(10, 100) for base 10.

Frequently Asked Questions

Why did LOG(0.5, 4) return NULL in MySQL?

MySQL explicitly checks B <= 1 for the two-argument LOG(B, X) form and returns NULL whenever the base is 1 or smaller. If you need fractional-base logs, compute LN(x) / LN(b) manually.

Is LOG(x) identical to LN(x) when given one argument?

Yes. In MySQL, LOG(x) with a single argument behaves identically to LN(x).

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum