MySQL LOG() Function
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 than0.base: Optional base value strictly greater than1.
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)returns3, whereasLOG(8, 2)returns0.3333. Some languages reverse this order, so double-check your argument positions. - Invalid base returns NULL: In MySQL,
LOG(b, x)requiresb > 1andx > 0. Passingb <= 1(such asLOG(1, 10),LOG(0.5, 4), orLOG(0, 10)) returnsNULL. - Zero or negative x:
LOG(0)andLOG(-10)returnNULLrather than raising a runtime error. - Assuming LOG(100) is base 10: Single-argument
LOG(100)uses basee(4.6052), NOT base10. UseLOG10(100)orLOG(10, 100)for base10.
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).
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.