If you’re getting an error that reads “ERROR: cannot take logarithm of a negative number” when using either the log()
function or log10()
function in PostgreSQL, it’s probably because you’re passing a negative value to the function.
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(-8);
Result:
ERROR: cannot take logarithm of a negative number
It’s the same with the log10()
function:
SELECT log10(-8);
Result:
ERROR: cannot take logarithm of a negative number
And we get the same error when using log()
if we pass a negative number for the base (even if the other argument is a positive value):
SELECT log(-10, 8);
Result:
ERROR: cannot take logarithm of a negative number
Solution
As the error message indicates, we need to change the negative number to something else. More specifically, we need to make the value greater than zero.
For example:
SELECT log(8);
Result:
0.9030899869919435
And when specifying a base for the log()
function, we need to specify a base that’s greater than zero:
SELECT log(2, 8);
Result:
3.0000000000000000