Finding Age Ranges With MySQL

August 25th, 2008 by admin

If you have ever stored a birth date in a MySQL database, it will not take long before you figure out that timestamps can be somewhat useless.  They are only good for dates between 1970 and 2038 on most systems.  Trying to find an age range using a Unix timestamp will uterly fail, especially if you want a platform independent solution.

There is a simple way to do this, and that is to first of all, save the birth dates in a “date” type field.  This will usually be by default a pattern like so “YEAR-MONTH-DAY” or “0000-00-00″.  Once your dates are in that format, you can use MySQL to do a comparison like so:

select * from user where birthday between DATE_SUB(CURDATE( ),INTERVAL 59 YEAR)
and DATE_SUB(CURDATE( ),INTERVAL 50 YEAR);

This will give you results from the “user” table for users who are between the ages of 50 to 59 providing that the birthday column is a “date” type.  It actually took me a while to figure this one out because I cannot ever remember needing such a data result.  Searching around the Net, I found no examples on how to exactly do this, so I hope this will help someone else a few hours of coding. :)

This entry was posted on Monday, August 25th, 2008 at 11:37 am and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply