Calculate the Age in Years in PostgreSQL

Postgres has the age() function that returns the age in years, months, and days based on two dates.

This works fine unless you only want to return the age in years.

For example, you simply want to return a person’s age based on their birthday. You want something like 32 instead of 32 years 4 mons 67 days, which is what age() is likely to return.

Fortunately there’s an easy way to do this in PostgreSQL.

If you only want the age in years, you can use either extract() or date_part() to get the year from the age() function’s return value.

Here’s an example that uses the date_part() function:

SELECT date_part('year', age(timestamp '2003-12-27'));

Result:

16.0

That’s how it appears when I run it in Azure Data Studio.

When I run it in psql, I get this:

16

Both extract() and date_part() return their results using the double precision data type.

You can convert this to an integer (or other data type) if required, by appending it with ::int.

SELECT date_part('year', age(timestamp '2003-12-27'))::int;

Result:

16