Fix Error “cannot take logarithm of zero” in PostgreSQL

If you’re getting an error that reads “ERROR: cannot take logarithm of zero” when using either the log() function or log10() function in PostgreSQL, it’s probably because you’re passing an argument of zero.

These functions require a value greater than zero. This is true even for the base argument of the log() function (the argument that specifies which base to use).

To fix this issue, be sure to pass a value greater than zero to these functions.

Example of Error

Here’s an example of code that produces the error:

SELECT log(0);

Result:

ERROR:  cannot take logarithm of zero

Same deal with the log10() function:

SELECT log10(0);

Result:

ERROR:  cannot take logarithm of zero

And we get the same error when using log() if we pass zero for the base (even if the other argument is greater than zero):

SELECT log(0, 20);

Result:

ERROR:  cannot take logarithm of zero

Solution

As the error message indicates, we need to change the zero to something else. More specifically, we need to make the value greater than zero.

For example:

SELECT log(35);

Result:

1.5440680443502757

And when specifying a base for the log() function, we need to specify a base that’s greater than zero:

SELECT log(2, 35);

Result:

5.1292830169449665

We also need to ensure that we don’t pass a negative value, otherwise we’ll get another error.