tags:

views:

41

answers:

2

Hi, I have a table where it stores the users. And i want a query to find the users which are between eg 25 years old and 31 years old. The age is stored at the mysql table as date (it stores the birthday). (eg: 1980-02-25 (yyyy-mm-dd))

How the query should be written in order to find each time the people who are between two given ages?

Thanks.

+3  A: 

You can either compute the necessary date range in your backend code, or in MySQL itself. Should you choose MySQL, here's what the query might look like:

SELECT user.* FROM user
  WHERE birthdate >= DATE_SUB(NOW(), INTERVAL 31 YEAR) 
  AND birthdate <= DATE_SUB(NOW(), INTERVAL 25 YEAR)
pix0r
thanks a lot! it worked! :)
Manolis
A: 

There is also the somewhat shorter BETWEEN clause for MySQL. I'd recommend CURDATE() instead of NOW() because it does not have the time component.

SELECT * FROM user
WHERE birthdate 
   BETWEEN 
   (CURDATE() - INTERVAL 31 YEAR) 
   AND 
   (CURDATE() - INTERVAL 25 YEAR)

Note: it's inclusive.

gahooa