Interview › Age from a date
SQL interview: age in years from a date of birth
DATEDIFF(year, dob, today) counts year boundaries, not birthdays.
Prompt. Age in completed years as of today.
Hint: DATEDIFF then subtract if the anniversary is still ahead
SELECT customer_id, dob,
DATEDIFF(year, dob, CAST(GETDATE() AS date))
- CASE WHEN DATEADD(year, DATEDIFF(year, dob, CAST(GETDATE() AS date)), dob)
> CAST(GETDATE() AS date)
THEN 1 ELSE 0 END AS age
FROM Customers;
Do not use this for anything legal without a test table of leap-day births.
Then write it on a ticket
Monday is free. A colleague asks, you type, we mark it.
Clock in free