MySQL LOG2() Function – Return the Base-2 Logarithm of a Value

In MySQL, the LOG2() function returns the base-2 logarithm of a specified value.

You provide the specified value as an argument when calling the function.

Syntax

This syntax goes like this:

LOG2(X)

Where X is the value for which you want the base-2 logarithm returned.

If X is less than or equal to 0.0E0, the function returns NULL and a warning is generated.

Example 1 – Basic Usage

Here’s a basic example to demonstrate how this function works.

SELECT LOG2(4);

Result:

+---------+
| LOG2(4) |
+---------+
|       2 |
+---------+

And here’s another example using various values.

SELECT 
  LOG2(8),
  LOG2(16),
  LOG2(128),
  LOG2(256),
  LOG2(1024);

Result:

+---------+----------+-----------+-----------+------------+
| LOG2(8) | LOG2(16) | LOG2(128) | LOG2(256) | LOG2(1024) |
+---------+----------+-----------+-----------+------------+
|       3 |        4 |         7 |         8 |         10 |
+---------+----------+-----------+-----------+------------+

Example 2 – Negative Value

Here’s an example of passing in a negative value.

SELECT LOG2(-4);

Result:

+----------+
| LOG2(-4) |
+----------+
|     NULL |
+----------+
1 row in set, 1 warning (0.01 sec)

This example returns a NULL value (and a warning) because the argument provided is less than 0.0E0.

Example 3 – Zero

Here’s an example of passing in zero as the argument (we get the same result as the previous example).

SELECT LOG2(0);

Result:

+---------+
| LOG2(0) |
+---------+
|    NULL |
+---------+
1 row in set, 1 warning (0.00 sec)

Example 4 – Expressions

You can also pass in expressions like this:

SELECT LOG2(2+2);

Result:

+-----------+
| LOG2(2+2) |
+-----------+
|         2 |
+-----------+

MySQL also has the LOG10() function that returns the base-10 logarithm of a value.

There’s also the LOG() function (and its synonym LN()) which returns the natural logarithm of a number.