Back to Blog
2 min read

How to Calculate Age in SQL (PostgreSQL, MySQL, and SQL Server)

Learn how to calculate age from date of birth in SQL with copy ready examples for PostgreSQL, MySQL, and SQL Server. Includes full years and common edge cases.

How to Calculate Age in SQL (PostgreSQL, MySQL, and SQL Server)

If you need to calculate age in SQL, the key question is what age means in your app. In most cases you want completed years, not just the difference between the current year and the birth year.

Quick option: check the result first

If you want to verify output before coding, use the age calculator with a date of birth and an as of date.

PostgreSQL

Postgres gives you a clean way to do this with age() and extract().

SELECT EXTRACT(YEAR FROM age(DATE '2026-03-26', DATE '1990-10-12')) AS age_years;

For a table with a date_of_birth column:

SELECT
  id,
  EXTRACT(YEAR FROM age(CURRENT_DATE, date_of_birth)) AS age_years
FROM users;

MySQL

In MySQL, TIMESTAMPDIFF(YEAR, ...) is the usual approach.

SELECT TIMESTAMPDIFF(YEAR, '1990-10-12', '2026-03-26') AS age_years;

Against a table:

SELECT
  id,
  TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) AS age_years
FROM users;

For many business cases this is enough, but test edge cases around birthdays and your server time zone.

SQL Server

A naive DATEDIFF(YEAR, ...) can overcount before the birthday. A safer pattern is to subtract 1 when the birthday has not happened yet.

DECLARE @dob date = '1990-10-12';
DECLARE @as_of date = '2026-03-26';

SELECT DATEDIFF(YEAR, @dob, @as_of)
  - CASE
      WHEN DATEFROMPARTS(YEAR(@as_of), MONTH(@dob), DAY(@dob)) > @as_of THEN 1
      ELSE 0
    END AS age_years;

Common pitfalls

  • Using year minus year only: this ignores whether the birthday already happened this year.

  • DateTime vs date: for date of birth, a date field is usually safer than a timestamp.

  • Leap day birthdays: decide how your app handles Feb 29 in non leap years, then test it explicitly.

When exact age matters

If you need years, months, and days, SQL gets more complex fast. In that case, it can be easier to validate the expected output with an online calculator and then match the same logic in code or SQL.

Related