Overview of LOG() in SQLite

The LOG() function in SQLite calculates the logarithm of a given number to a specified base, with 10 being the default base.

This is helpful for logarithmic transformations or calculations requiring a specific base (e.g., base 10 for common logarithms or base 2 for binary logarithms).

Syntax

You can call LOG() with either one or two arguments:

LOG(X)
LOG(B, X)

Where:

  • B: The base of the logarithm (must be greater than 0 and not equal to 1).
  • X: The number for which you want to calculate the logarithm (must be greater than 0).

When using the first syntax (i.e. when B is omitted), LOG() calculates the base 10 logarithm of X.

Example Using LOG(X) Syntax

Here’s an example that uses the first syntax:

SELECT LOG(100), 
       LOG(32), 
       LOG(25);

Result:

+----------+------------------+------------------+
| LOG(100) | LOG(32) | LOG(25) |
+----------+------------------+------------------+
| 2.0 | 1.50514997831991 | 1.39794000867204 |
+----------+------------------+------------------+

I didn’t specify a base, and so these all used base 10.

Example Using LOG(B,X) Syntax

This time, let’s specify a base for each number:

SELECT LOG(10, 100) AS log_base10_result, 
       LOG(2, 32) AS log_base2_result, 
       LOG(5, 25) AS log_base5_result;

Result:

+-------------------+------------------+------------------+
| log_base10_result | log_base2_result | log_base5_result |
+-------------------+------------------+------------------+
| 2.0 | 5.0 | 2.0 |
+-------------------+------------------+------------------+

Rounding the Result

Sometimes the result can include a lot of decimal places. If we want less decimal places, we can combine LOG() with the ROUND() function to round the result.

For example,

SELECT LOG(5, 19) AS unrounded,
       ROUND(LOG(5, 19), 2) AS rounded;

Result:

+------------------+---------+
| unrounded | rounded |
+------------------+---------+
| 1.82948280043515 | 1.83 |
+------------------+---------+

There’s also a LOG10() function that does the same thing as the first syntax of LOG() (it returns the base 10 logarithm for its argument.

Therefore, if you’re only interested in base 10, then you could use either LOG(X) or LOG10(X).