Average Age from DOB Field - MySQL / PHP

sluggerdog picture sluggerdog · Nov 14, 2012 · Viewed 7.8k times · Source

I wasn't sure how I could calculate the average age of my contacts who all exist in a mysql table with a DOB date field such as YYYY-MM-DD.

Is there a way to do with with a MySQL call (please note I am using cakephp but that shouldn't be an issue)

Thanks

Answer

Bailey Parker picture Bailey Parker · Nov 14, 2012

You can determine age by using DATEDIFF():

DATEDIFF(TO_DAYS(NOW()), TO_DAYS(DOB))

The average is found in MySQL using AVG():

AVG(Column)

So combine those:

SELECT AVG(DATEDIFF(TO_DAYS(NOW()), TO_DAYS(DOB))) as `Average` FROM Contacts;

Note that this returns the average age in days, not years. To obtain years you can average the years part of each date:

SELECT AVG(DATEDIFF(YEAR(NOW()), YEAR(DOB))) as `Average` FROM Contacts;

Or as @TimDearborn suggested, divide the day average by 365.242199.