PostgreSQL: age Function
This PostgreSQL tutorial explains how to use the PostgreSQL age function with syntax and examples.
Description
The PostgreSQL age function returns the number of years, months, and days between two dates.
Syntax
The syntax for the age function in PostgreSQL is:
age( [date1,] date2 )
Parameters or Arguments
- date1 and date2
- The two dates to calculate the difference between.
Calculation
The age function performs two different calculations depending on what parameters are provided.
If date1 is provided, the age function performs the following calculation:
date1 - date2
If date1 is NOT provided, the age function performs the following calculation:
current date - date2
Note
The age function will return the result as one of the following formats:
- xxx year(s) xxx mon(s) xxx day(s)
- xxx mon(s) xxx day(s)
- xxx day(s)
Applies To
The age function can be used in the following versions of PostgreSQL:
- PostgreSQL 9.4, PostgreSQL 9.3, PostgreSQL 9.2, PostgreSQL 9.1, PostgreSQL 9.0, PostgreSQL 8.4
Example
Let's look at some PostgreSQL age function examples and explore how to use the age function in PostgreSQL.
For example:
postgres=# SELECT age(timestamp '2014-01-01'); (current date is '2014-04-25') age ---------------- 3 mons 24 days (1 row) postgres=# SELECT age(timestamp '2014-04-25', timestamp '2014-01-01'); age ---------------- 3 mons 24 days (1 row) postgres=# SELECT age(timestamp '2014-04-25', timestamp '2014-04-17'); age -------- 8 days (1 row) postgres=# SELECT age(current_date, timestamp '2012-09-16'); age ---------------------- 1 year 7 mons 9 days (1 row)
Advertisements