No one stores age in a database. Age is a derived attribute. We usually store date of birth of someone.
As a noob, I put the dob field as INT(10)
in my database. To select e.g. users between 18 – 25 years old, I’d run the following SQL query:
SELECT *
FROM users
WHERE dob <= unix_timestamp(NOW() <= (NOW() - INTERVAL 18 YEAR)
AND dob >= unix_timestamp(NOW() - INTERVAL 25 YEAR)
It worked fine until I realized that it would not work for people who are born before 1970. PHP’s strtotime() function was returning a negative number as timestamp which is correct but the DB would refuse to put it since it was INT.
After some more googling, I came to know that I should have used DATE type.
After that, everything gets solved.
SELECT *
FROM users
WHERE dob <= (NOW() - INTERVAL 18 YEAR)
AND dob >= (NOW() - INTERVAL 90 YEAR)
The advantage now is that it can be used to POST with HTML5 forms and used as value directly.