Compute the base-2 (binary) logarithm of a positive number.
LOG2(expr)
## Overview Returns the base-2 (binary) logarithm of the input. LOG2 is the preferred function for information-theoretic calculations (Shannon entropy in bits, mutual information), for reasoning about the number of bits required to represent a value, and for algorithm-complexity estimates expressed in bits. For an exact power of 2 (such as 2, 8, 1024, or 2^30) LOG2 returns an exact integer in floating-point, without the rounding residue that LOG(2, x) would produce from the internal LN(x) / LN(2) division. ## Behavior - Domain: (0, infinity). Zero and negative values return NULL. - Range: all real numbers. - Returns NULL if the argument is NULL. - Is strictly increasing. - LOG2 of an exact power of 2 returns an exact integer in floating-point. ## Numeric precision - Uses the IEEE 754 double-precision log2 routine. - For integer powers of 2 within the representable range, the result is an exact integer. - Near x = 1, LOG2 loses precision. Prefer LOG1P(x - 1) / LN(2) when the input is very close to 1. ## Compatibility - Conforms to the SQL standard definition of LOG2 as a scalar DOUBLE function with domain x > 0. - Matches typical mathematical library implementations.
| Name | Type | Description |
|---|---|---|
expr | Specifies the positive input whose base-2 logarithm is returned. Must be strictly greater than 0; zero and negative values yield NULL. |
-- Basic literal: log2 of 2 is 1
SELECT LOG2(2);
-- Result: 1.0
-- log2 of 8 is 3
SELECT LOG2(8);
-- Result: 3.0
-- log2 of 1024 is 10
SELECT LOG2(1024);
-- Result: 10.0
-- log2 of 1 is 0
SELECT LOG2(1);
-- Result: 0.0
-- Domain violation
SELECT LOG2(0), LOG2(-8);
-- Result: NULL, NULL
-- Column use: bit-count of a value (approximate, for positive integers)
SELECT event_id, CEIL(LOG2(value + 1)) AS bits_needed
FROM analytics.events.counters
WHERE value >= 0;