Skip to content
Advertisement

Calculate age in MySQL (InnoDB)

If I have a person’s 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?

Advertisement

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 
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement