If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Age Calculations

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 11-04-06, 14:01
Pizzor2000 Pizzor2000 is offline
Registered User
 
Join Date: Dec 2005
Posts: 14
Age Calculations

I have a table of Users on a MySQL database, which includes a field, BirthDate.

I would like to be able to:
  1. Calculate the User's age, based on the BirthDate, to return in a query, and
  2. Filter by that calculated age (i.e.: Find everyone from 18-25).
I have found various examples of returning the age in a query, but I haven't found the best way to filter by age, age range, etc.
Reply With Quote
  #2 (permalink)  
Old 11-04-06, 15:10
dbmab dbmab is offline
Registered User
 
Join Date: Apr 2006
Location: Denver, Co. USA
Posts: 240
A HAVING clause should work. The following is an expansion of the PET tutorial example in the msyql manual (untested but should work) -

SELECT name, birth, CURDATE(),
(YEAR(CURDATE())-YEAR(birth)) - (RIGHT(CURDATE(),5)<RIGHT(birth,5))
AS age
FROM pet
HAVING age >= 18 AND age <= 25

You could also put the age calculation into a WHERE clause with the comparisons.
Reply With Quote
  #3 (permalink)  
Old 11-05-06, 01:17
Pizzor2000 Pizzor2000 is offline
Registered User
 
Join Date: Dec 2005
Posts: 14
Thanks. I originally tried it using a WHERE clause on the age alias, and it didn't work. I tried your example with the HAVING clause, and it did the trick.
Reply With Quote
  #4 (permalink)  
Old 11-05-06, 06:41
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
do you undestand what this is doing? --
Code:
 ... - (RIGHT(CURDATE(),5)<RIGHT(birth,5))
if not, i would suggest that you re-write it using a CASE expression, because it won't work in any other database written like that
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On