In MariaDB, LOG2()
is a built-in function that returns the base-2 logarithm of its argument.
Syntax
The syntax goes like this:
LOG2(X)
Where X
is the value for which to return the base-2 logarithm.
Example
Here’s an example to demonstrate:
SELECT LOG2(3);
Result:
+--------------------+ | LOG2(3) | +--------------------+ | 1.5849625007211563 | +--------------------+
Here are some more:
SELECT
LOG2(2),
LOG2(4),
LOG2(8),
LOG2(16);
Result:
+---------+---------+---------+----------+ | LOG2(2) | LOG2(4) | LOG2(8) | LOG2(16) | +---------+---------+---------+----------+ | 1 | 2 | 3 | 4 | +---------+---------+---------+----------+
Argument Ranges
If X
is less than or equal to 0
, then NULL
is returned with a warning.
SELECT
LOG2(0),
LOG2(-1);
Result:
+---------+----------+ | LOG2(0) | LOG2(-1) | +---------+----------+ | NULL | NULL | +---------+----------+ 1 row in set, 2 warnings (0.000 sec)
Let’s check the warnings:
SHOW WARNINGS;
Result:
+---------+------+---------------+ | Level | Code | Message | +---------+------+---------------+ | Warning | 1365 | Division by 0 | | Warning | 1365 | Division by 0 | +---------+------+---------------+
Non-Numeric Arguments
Here’s an example of what happens when we provide non-numeric arguments:
SELECT LOG2('Dog');
Result:
+-------------+ | LOG2('Dog') | +-------------+ | NULL | +-------------+ 1 row in set, 2 warnings (0.000 sec)
Let’s see the warning:
SHOW WARNINGS;
Result:
+---------+------+-----------------------------------------+ | Level | Code | Message | +---------+------+-----------------------------------------+ | Warning | 1292 | Truncated incorrect DOUBLE value: 'Dog' | | Warning | 1365 | Division by 0 | +---------+------+-----------------------------------------+
Null Arguments
LOG2()
returns null
if its argument is null
:
SELECT LOG2(null);
Result:
+------------+ | LOG2(null) | +------------+ | NULL | +------------+
Missing Arguments
Calling LOG2()
with the wrong number of arguments, or without any arguments results in an error:
SELECT LOG2();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'LOG2'
And:
SELECT LOG2(10, 2);
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'LOG2'