PostgreSQL LN() Function
Summary: in this tutorial, you will learn how to use the PostgreSQLLN()
function to calculate the natural logarithm of a number.
Introduction to the PostgreSQL LN() function
The natural logarithm is a function that represents the logarithm to base e, where e is Euler’s number, which is approximately equal to2.71828
.
In Math, the natural logarithm of a x is denoted as ln(x).
If ln(x) = y, then ey = x.
In PostgreSQL, you use theLN()
function to calculate the natural logarithm of a number.
Here’s the syntax of theLN()
function:
LN(n)
In this syntax:
n
is a number with the type numeric or double precision. It can be a literal number, an expression, or a table column.n
cannot be zero.
TheLN()
function returns the natural logarithm ofn
with the type corresponding to the type ofn
. It returnsNULL
if n isNULL
.
If n is a string, theLN()
function will convert it to a type numeric or double precision value. If the conversion fails, theLN()
function raises an error.
TheLN()
function is the inverse of theEXP()
function that returns the exponential value of a number.
PostgreSQL LN() function examples
Let’s take some examples of using theLN()
function.
1) Basic PostgreSQL LN() function examples
The following example uses theLN()
function to return the natural logarithm of 10:
SELECT LN(10) result;
Output:
result------------------- 2.302585092994046
The following statement uses theLN()
function to return the natural logarithm of e:
SELECT LN(EXP(1)) result;
Output:
result-------- 1
In this example, theEXP
(1) function returns e1, which is e. Then, theLN()
function returns the natural logarithm of e, which returns 1.
2) Using the LN() function with text
The following example uses theLN()
function to calculate the natural logarithm of a numeric string ’10’
SELECT LN('10') result;
Output:
result------------------- 2.302585092994046
In this example, theLN()
function converts the string ’10’ to a number before calculating the natural logarithm.
The following example attempts to calculate the natural logarithm of the string ’10x’:
SELECT LN('10x') result;
The function raises an error because it cannot convert the string ’10x’ to a number:
ERROR: invalid input syntaxfor type double precision:"10x"LINE 1:SELECT LN('10x') result; ^
Summary
- Use the
LN()
function to calculate the natural logarithm of a number.
Last updated on