Sitemap
Data SQL

Data SQL

Member-only story

Age Function in SQL

2 min readMar 21, 2024

--

Hi,

These age functions in SQL allow you to calculate age in years, months, or a combination of both, considering leap years and complete months accurately. You can use these functions in your SQL queries to derive age-related insights from your data.

Press enter or click to view image in full size
Photo by Annie Spratt on Unsplash

Calculate Age in Years:

SELECT 
DATEDIFF(YEAR, BirthDate, GETDATE()) AS Age
FROM YourTable;

Calculate Age in Years and Months:

SELECT 
DATEDIFF(YEAR, BirthDate, GETDATE()) -
CASE
WHEN DATEADD(YEAR, DATEDIFF(YEAR, BirthDate, GETDATE()), BirthDate) > GETDATE() THEN 1
ELSE 0
END AS Years,
DATEDIFF(MONTH,
DATEADD(YEAR, DATEDIFF(YEAR, BirthDate, GETDATE()) -
CASE
WHEN DATEADD(YEAR, DATEDIFF(YEAR, BirthDate, GETDATE()), BirthDate) > GETDATE() THEN 1
ELSE 0
END, BirthDate),
GETDATE()) AS Months
FROM YourTable;
Press enter or click to view image in full size
Photo by ThisisEngineering RAEng on Unsplash

Calculate Age in…

--

--