PostgreSQL age() Function
The PostgreSQL age()
function calculate the age according to the specified birthday and returns the age in the format of x years x mons x days
.
age()
Syntax
The syntax of the PostgreSQL age()
function comes in two forms:
age(date, birthday) -> interval
or
age(birthday) -> interval
Parameters
date
-
Optional. The date on which to calculate the age.
birthday
-
Required. The Birthday.
Return value
The PostgreSQL age(date, birthday)
function returns the age of the specified date according to the specified birthday.
The PostgreSQL age(birthday)
function returns the current age based on specified birthday.
The PostgreSQL age(birthday)
function returns an interval value in the format x years x mons x days
.
If the provided birthday is greater than the provided date or now, this function will return a negative interval.
age()
Examples
This example shows how to use the PostgreSQL age()
function to calculate the current age from the birthday 2001-01-01
.
SELECT age(timestamp '2001-01-01');
age
-------------------------
21 years 4 mons 12 days
You can also calculate his age on a certain date like 2010-02-02
:
SELECT age(timestamp '2010-02-02', timestamp '2001-01-01');
age
---------------------
9 years 1 mon 1 day
Let’s look at more examples:
SELECT
age('2010-02-01', '2001-01-01'),
age('2010-01-01', '2001-01-01'),
age('2001-02-01', '2001-01-01'),
age('2001-01-02', '2001-01-01');
age | age | age | age
---------------+---------+-------+-------
9 years 1 mon | 9 years | 1 mon | 1 day