MySQL LOG() Function – Return the Natural Logarithm of a Value

In MySQL, the LOG() function returns the natural logarithm of a specified value.

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

Syntax

This function can be used with either one argument or two. Using one argument looks like this:

LOG(X)

Where X is the value for which you want the natural logarithm returned.

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

It can also be used with two arguments, like this:

LOG(B,X)

In this case, the function returns the logarithm of X to the base B. If X is less than or equal to 0, or if B is less than or equal to 1, then NULL is returned.

Example 1 – One Argument

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

SELECT LOG(3);

Result:

+--------------------+
| LOG(3)             |
+--------------------+
| 1.0986122886681098 |
+--------------------+

And here’s another example using a different value.

SELECT LOG(0.3);

Result:

+---------------------+
| LOG(0.3)            |
+---------------------+
| -1.2039728043259361 |
+---------------------+

Example 2 – Negative Value

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

SELECT LOG(-3);

Result:

+---------+
| LOG(-3) |
+---------+
|    NULL |
+---------+

This example returns a NULL value 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 LOG(0);

Result:

+--------+
| LOG(0) |
+--------+
|   NULL |
+--------+

Example 4 – Expressions

You can also pass in expressions like this:

SELECT LOG(2+3);

Result:

+--------------------+
| LOG(2+3)           |
+--------------------+
| 1.6094379124341003 |
+--------------------+

Example 5 – Two Arguments

Here’s an example to demonstrate how this function works using two arguments.

SELECT LOG(10, 100);

Result:

+--------------+
| LOG(10, 100) |
+--------------+
|            2 |
+--------------+

And using another example:

SELECT LOG(100, 10);

Result:

+--------------+
| LOG(100, 10) |
+--------------+
|          0.5 |
+--------------+

Example 6 – NULL Result

As mentioned, if the first argument is 1 or less, a NULL value is returned.

SELECT LOG(1, 10);

Result:

+------------+
| LOG(1, 10) |
+------------+
|       NULL |
+------------+

And a NULL value is also returned if the second argument is equal to zero or less:

SELECT LOG(10, 0);

Result:

+------------+
| LOG(10, 0) |
+------------+
|       NULL |
+------------+

MySQL also has the LN() function that is synonymous with the LOG() function (but only using the single-argument syntax).

MySQL also has the EXP() function that is the inverse of the LOG() function when using the single-argument syntax.