MySQL LOG2() Function
MySQL LOG2() Function: Computing Base-2 Logarithms
The LOG2() function calculates the base-2 (binary) logarithm of a positive number in MySQL. It tells you what exponent 2 must be raised to in order to equal x.
Engineers reach for LOG2() when calculating required bit counts, binary tree depths, storage chunk tiers, or doubling intervals in growth reports. For example, LOG2(64) returns 6 because 2^6 = 64.
Syntax
LOG2(x)
x: Numeric value strictly greater than0.
Practical Example
Suppose demo_products sells cloud storage tiers with capacities in gigabytes (capacity_gb). You can calculate the exact binary exponent and bits needed to address each storage tier with LOG2().
SELECT
product_id,
plan_name,
capacity_gb,
ROUND(LOG2(capacity_gb), 2) AS power_of_two,
CEIL(LOG2(capacity_gb)) AS bits_required
FROM demo_products
WHERE capacity_gb IS NOT NULL;
| product_id | plan_name | capacity_gb | power_of_two | bits_required |
|---|---|---|---|---|
| 71 | Starter 16GB | 16 | 4.00 | 4 |
| 72 | Team 250GB | 250 | 7.97 | 8 |
| 73 | Archive 1024GB | 1024 | 10.00 | 10 |
| 74 | Free Trial 0GB | 0 | NULL | NULL |
Tier 72 has 250 GB, which falls just under 256 (2^8), so CEIL(LOG2(250)) reports 8 bits. Tier 74 has 0 GB and safely produces NULL.
Common Mistakes & NULL Behavior
- Inputs less than or equal to zero: Passing
0or any negative number toLOG2()returnsNULLsilently. AddWHERE val > 0ifNULLbuckets would skew aGROUP BYsummary. - Testing exact powers of two with floats: Checking
LOG2(col) = FLOOR(LOG2(col))works for modest integers, though for hugeBIGINTvalues floating-point precision can blur results. ForBIGINTbit checks, bitwise(n & (n - 1)) = 0is safer. - NULL inputs:
LOG2(NULL)returnsNULL.
Frequently Asked Questions
What does LOG2(1) return in MySQL?
LOG2(1) returns 0, because 2^0 = 1.
Is LOG2(x) faster or more accurate than LOG(2, x)?
MySQL computes LOG2(x) directly using the C library's base-2 logarithm, avoiding extra division rounding and keeping SQL queries shorter to read.
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.