// SQL snippet

Compute age in years, months and days in SQL

A person's age is years since their last birthday, which a naive DATEDIFF(YEAR, ...) gets wrong by one around birthdays.

Main statement
PostgreSQL
次もカバーします
SQL Server MySQL

The task

PostgreSQL's age() returns an interval that already respects whether the birthday has passed this year.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT
    EXTRACT(YEAR  FROM age(CURRENT_DATE, birth_date))::int AS years,
    EXTRACT(MONTH FROM age(CURRENT_DATE, birth_date))::int AS months,
    EXTRACT(DAY   FROM age(CURRENT_DATE, birth_date))::int AS days
FROM patients;

仕組み

age(end, start) returns a year-month-day interval computed with calendar rules, not fixed day counts. Extracting the three parts gives the components people expect. A plain DATEDIFF(YEAR, birth_date, today) style difference is off by one for everyone whose birthday has not happened yet this year.

Variations

MySQL

MySQL
SELECT TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) AS age_years
FROM patients;

SQL Server

SQL Server
SELECT
    DATEDIFF(YEAR, birth_date, GETDATE())
      - CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, birth_date, GETDATE()), birth_date) > GETDATE()
             THEN 1 ELSE 0 END AS age_years
FROM patients;

Questions that come up

What about February 29 birthdays?

Engines disagree. PostgreSQL's age() and MySQL's TIMESTAMPDIFF only count the year on March 1 in non-leap years: someone born 2024-02-29 is still 2 on 2027-02-28. The SQL Server CASE counts it on Feb 28, because DATEADD(YEAR, 3, '2024-02-29') returns 2027-02-28. Legal rules differ by country too, so if it matters, decide the rule and test it on Feb 28 and Mar 1.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.