PostgreSQL AGE Function: How to Calculate Date Differences
In this article
The PostgreSQL AGE function calculates the precise interval between two dates or timestamps, returning a human-readable duration like '2 years 3 months 15 days'. It requires no additional extensions or setup—just a working PostgreSQL database with access to standard date/time functions.
What You'll Need
- A running PostgreSQL server (version 9.0 or later)
- Access to a database with read permissions on tables containing date or timestamp columns
- A client tool like psql, pgAdmin, DBeaver, or any SQL interface that connects to PostgreSQL
Step-by-Step
- Connect to your PostgreSQL database using your preferred client. For example, in psql, type
psql -U your_username -d your_databaseand enter your password when prompted. - Identify the date or timestamp columns you want to compare. These can be from a single row (e.g., birth date and today) or between two columns in a table (e.g., order_date and shipment_date).
- Use the AGE function with one argument to calculate the interval from a given date to the current date. For example:
SELECT AGE('2020-05-15');This returns the time elapsed since May 15, 2020, up to today. - To compare two specific dates, pass both as arguments to AGE. Example:
SELECT AGE('2023-12-01', '2021-08-10');This returns the interval between August 10, 2021, and December 1, 2023. - Combine AGE with column names in a SELECT statement. For instance, if you have a table named
employeeswith ahire_datecolumn, run:SELECT name, AGE(CURRENT_DATE, hire_date) AS tenure FROM employees;This calculates each employee’s tenure in years, months, and days. - If you need to format the output for reports, wrap AGE in a CAST or use EXTRACT to isolate parts like years or months. Example:
SELECT EXTRACT(YEAR FROM AGE('2024-06-01', '1990-03-15')) AS years_old;This returns only the number of full years. - Test the function with edge cases: leap years, month-end dates, and timestamps with time zones. For example:
SELECT AGE('2024-02-29 14:30:00', '2020-02-29 14:30:00');PostgreSQL handles leap days correctly. - Store the result in a view or CTE if you reuse it frequently. Example:
CREATE VIEW employee_tenure AS SELECT name, AGE(CURRENT_DATE, hire_date) AS tenure FROM employees;Then query it withSELECT * FROM employee_tenure;
Common Mistakes
- Passing a string that isn’t a valid date format, like
AGE('05/15/2020')—PostgreSQL expects ISO format (YYYY-MM-DD) unless explicitly cast. UseAGE('2020-05-15'::date)if you have non-standard strings. - Using AGE with NULL values. If either argument is NULL, the result is NULL. Always check for NULLs with
COALESCEorWHERE column IS NOT NULL. - Confusing AGE with subtraction. You cannot subtract two dates using
-and expect a readable interval; that returns an integer number of days. AGE is the only function that returns formatted intervals. - Assuming AGE works with time-only values. AGE requires date or timestamp inputs. If you have only a time, combine it with a date first using
timestamp '2024-01-01' + time '14:30:00'. - Forgetting that AGE returns an interval type, not a number. You cannot directly compare it to integers or use it in arithmetic without extracting components first.
Tips
- Use
CURRENT_DATEorCURRENT_TIMESTAMPto dynamically reference today’s date without hardcoding values. - For age calculations in human-readable reports, combine AGE with
TO_CHAR:SELECT TO_CHAR(AGE('2024-01-01'), 'YYYY" years "MM" months "DD" days"') AS formatted_age; - When comparing timestamps with time zones, ensure both are in the same zone. Use
AT TIME ZONEto convert:AGE('2024-06-01 10:00:00+00'::timestamptz, '2024-01-01 10:00:00-05'::timestamptz). - Use AGE in ORDER BY clauses to sort records by duration:
SELECT * FROM events ORDER BY AGE(CURRENT_DATE, event_date) DESC; - For performance on large tables, avoid calculating AGE on every row unless necessary. Consider adding a computed column or materialized view if the data changes infrequently.
Troubleshooting
- Query returns NULL: Verify that both date arguments are not NULL. Run
SELECT your_column IS NULL FROM your_table LIMIT 5;to check. UseWHERE your_date IS NOT NULLto filter them out. - Invalid date format error: Ensure date strings are in ISO format (YYYY-MM-DD) or use explicit casting:
AGE('15-05-2020'::date)may work if your locale allows it, but always prefer'2020-05-15'. - AGE returns unexpected results: Confirm you’re not mixing date and timestamp types. If one argument is a timestamp and the other a date, PostgreSQL promotes the date to timestamp at midnight. Use
DATE()orCAST(... AS date)to standardize. - Function not recognized: AGE is built-in. If you get a function not found error, your connection may be to a non-PostgreSQL database or an outdated version. Check with
SELECT version();Ensure you’re connected to PostgreSQL 9.0+. - Performance is slow on large datasets: Add an index on the date column being compared. While AGE itself can’t be indexed, the source column can:
CREATE INDEX idx_hire_date ON employees(hire_date);
Frequently Asked Questions
Can I use AGE to calculate someone’s age in years only?
Yes, useEXTRACT(YEAR FROM AGE(birth_date)) to get the full years between a birth date and today.
Does AGE account for leap years correctly?
Yes, PostgreSQL’s interval calculations fully account for leap years, leap seconds, and varying month lengths.Can AGE work with time zones?
Yes, if you use timestamp with time zone (timestamptz) inputs. AGE automatically normalizes time zones before calculating the difference.What’s the difference between AGE and just subtracting two dates?
Subtracting two dates returns an integer (number of days). AGE returns an interval with years, months, and days, making it more human-readable and precise for age or tenure.Can I use AGE in a WHERE clause to find people older than 18?
Not directly. UseEXTRACT(YEAR FROM AGE(birth_date)) > 18 instead. AGE returns an interval, which can’t be compared to integers without extraction.