SQL

Calculate Age from Birthdate in SQL

Learn to accurately calculate a person's age from their birthdate using standard SQL functions, considering current date and time differences for precision.

-- PostgreSQL
SELECT name, birthdate, AGE(CURRENT_DATE, birthdate) AS age
FROM Users;

-- MySQL (simplified, returns years only)
-- SELECT name, birthdate, TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) AS age
-- FROM Users;

-- SQL Server (simplified, returns years only)
-- SELECT name, birthdate, DATEDIFF(year, birthdate, GETDATE()) -
--     CASE
--         WHEN MONTH(birthdate) > MONTH(GETDATE()) OR
--              (MONTH(birthdate) = MONTH(GETDATE()) AND DAY(birthdate) > DAY(GETDATE()))
--         THEN 1
--         ELSE 0
--     END AS age
-- FROM Users;
How it works: This query demonstrates how to calculate the age of individuals based on their birthdate stored in a database. It utilizes database-specific date functions like AGE() in PostgreSQL, TIMESTAMPDIFF() in MySQL, or DATEDIFF() with conditional logic in SQL Server to precisely determine the difference in years between the birthdate and the current date, providing accurate age calculation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs