MySQL LOG2() Function
The MySQL LOG2() function returns the base-2 logarithm of a given number. In special cases it returns the following:
- If the number is less than or equal to 0, then NULL is returned.
Syntax
LOG2(number)
Parameters
number |
Required. Specify the number. Must be greater than 0. |
Return Value
Returns the base-2 logarithm of a given number.
Example 1:
The example below shows the usage of LOG2() function.
mysql> SELECT LOG2(1); Result: 0 mysql> SELECT LOG2(1.5); Result: 0.5849625007211562 mysql> SELECT LOG2(2); Result: 1 mysql> SELECT LOG2(5); Result: 2.321928094887362 mysql> SELECT LOG2(10); Result: 3.3219280948873626 mysql> SELECT LOG2(0); Result: NULL
Example 2:
Consider a database table called Sample with the following records:
Data | x |
---|---|
Data 1 | 0.5 |
Data 2 | 1 |
Data 3 | 5 |
Data 4 | 10 |
Data 5 | 50 |
The statement given below can be used to calculate the base-2 logarithm of column x.
SELECT *, LOG2(x) AS LOG2_Value FROM Sample;
This will produce the result as shown below:
Data | x | LOG2_Value |
---|---|---|
Data 1 | 0.5 | -1 |
Data 2 | 1 | 0 |
Data 3 | 5 | 2.321928094887362 |
Data 4 | 10 | 3.3219280948873626 |
Data 5 | 50 | 5.643856189774724 |
❮ MySQL Functions