user559142 user559142 - 5 months ago 19
MySQL Question

Calculate Age in MySQL (InnoDb)

If I have a persons date of birth stored in a table in the form

dd-mm-yyyy
and I subtract it from the current date, what format is the date returned in?

How can I use this returned format to calculate someone's age?

Answer

If the value is stored as a DATETIME data type:

SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age 
  FROM YOUR_TABLE

Less precise when you consider leap years:

SELECT DATEDIFF(CURRENT_DATE, STR_TO_DATE(t.birthday, '%d-%m-%Y'))/365 AS ageInYears
  FROM YOUR_TABLE t 
Comments