The AGE function helps you find the difference between two dates or times. It tells you how much time has passed between them in years, months, and days.
0
0
AGE function for differences in PostgreSQL
Introduction
To find out how old someone is based on their birthdate.
To calculate how long ago an event happened from today.
To measure the time difference between two project deadlines.
To check how long a product has been in stock.
To find the duration between a start date and an end date in reports.
Syntax
PostgreSQL
AGE(timestamp1, timestamp2) -- or -- AGE(timestamp) -- timestamp1 and timestamp2 are dates or timestamps -- If only one timestamp is given, AGE calculates difference from current date/time
If you give two timestamps, AGE returns the difference between them.
If you give only one timestamp, AGE returns the difference between that timestamp and the current date/time.
Examples
This finds the difference between June 1, 2024, and June 1, 2020.
PostgreSQL
SELECT AGE('2024-06-01', '2020-06-01');
This finds the difference between the current date/time and June 1, 2024.
PostgreSQL
SELECT AGE('2024-06-01');
This finds the difference including time between two timestamps.
PostgreSQL
SELECT AGE(TIMESTAMP '2024-06-01 12:00:00', TIMESTAMP '2023-01-01 08:30:00');
Sample Program
This query calculates the age difference between June 1, 2024, and June 1, 2020.
PostgreSQL
SELECT AGE('2024-06-01', '2020-06-01') AS difference;
OutputSuccess
Important Notes
The result shows years, months, and days separately for easy reading.
AGE returns an interval type, which you can use in other calculations if needed.
If you swap the two dates, the result will be negative, showing the reverse difference.
Summary
AGE calculates the time difference between two dates or timestamps.
It returns the difference in years, months, and days as an interval.
You can use it with one or two timestamps depending on your need.