← Back to SQL, page 8

sql-0158 · Medium mid

Write a query that returns each employee's age in whole years on 2026-12-01, given a birth date.

Subtract the birth year from the reference year, then subtract one more if the birthday has not happened yet that year: compare the month-day parts as text. Dividing days by 365.25 is close but can be off by one around birthdays. PostgreSQL has age() and EXTRACT(YEAR FROM age(...)).

Full answer
sql
WITH p(name, born) AS (VALUES ('A', '1996-12-01'), ('B', '1996-12-02'), ('C', '2000-02-29'))
SELECT name, born,
       CAST(strftime('%Y', '2026-12-01') AS INTEGER) - CAST(strftime('%Y', born) AS INTEGER)
       - (strftime('%m-%d', '2026-12-01') < strftime('%m-%d', born)) AS age
FROM p ORDER BY name;
namebornage
A1996-12-0130
B1996-12-0229
C2000-02-2926

The year difference over-counts by one for anyone whose birthday falls later in the year. Comparing 'MM-DD' strings fixes it, because ISO month-day text sorts in calendar order. Someone born on 2 December is still 29 on 1 December, and someone born on 1 December has just turned 30.

PostgreSQL's age returns an interval of years, months and days:

sql
SELECT name, EXTRACT(YEAR FROM age(DATE '2026-12-01', born))::int AS age
FROM (VALUES ('A', DATE '1996-12-01'), ('B', DATE '1996-12-02'), ('C', DATE '2000-02-29')) AS p(name, born) ORDER BY name;
nameage
A30
B29
C26

The 29 February case needs a rule (is the birthday 28 February or 1 March in non-leap years?). Decide it with the business; the string comparison above treats 1 March as the birthday.

sql
WITH p(name, born) AS (VALUES ('A', '1996-12-01'), ('B', '1996-12-02'), ('C', '2000-02-29'))
SELECT name, born,
       CAST(strftime('%Y', '2026-12-01') AS INTEGER) - CAST(strftime('%Y', born) AS INTEGER)
       - (strftime('%m-%d', '2026-12-01') < strftime('%m-%d', born)) AS age
FROM p ORDER BY name;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Year difference minus one if the birthday has not passed
  • Compare 'MM-DD' strings for the birthday check
  • PostgreSQL: EXTRACT(YEAR FROM age(ref, birth))
  • Dividing days by 365.25 can be off by one

Common mistakes

  • Using the year difference alone
  • Ignoring 29 February births

Follow-ups

  • How would you list employees with birthdays next week?
  • How would you compute age in months?

Tips

  • Test with a birthday the day before and the day of the reference date