Question

How do I convert birthdate to age in a sql statement

Asked by: bolenka

Hi all. I am trying to get all records back from a database and I am passing in some parameters to get some records back. The parameters I am passing in are the ages of people that I want to return...a min age and max age, zipcode, miles and gender...basic people searching.

In the code below, see how I am selecting birthdate?...I don't want to do that....I want to convert birthdate to age and then match the min age and match age accordingly...meaning...I want the search to return all records that are between certain ages, but I don't want to store the age in the db because its always changing...I want it to be calculated from Birthdate...can somebody please help???

SELECT FirstName, LastName, City, [State], ZipCode, Comment, Birthdate FROM ProfilePreferences 
WHERE ZipCode 
IN( some other code here) 
and Gender=@Gender
and Age >= @AgeMin and Age<=@AgeMax

                                  
1:
2:
3:
4:
5:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-09 at 19:21:06ID24720182
Tags

TSQL

,

SQL

,

SQL Server

,

Sql Server Stored procedures

,

SQL Server 2008

Topics

Databases Miscellaneous

,

SQL Query Syntax

,

SQL Server 2008

Participating Experts
4
Points
500
Comments
23

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Convert GetDate()-BirthDate to Age
    Looking for the correct sql syntax to return the person's age from a stored BirthDate.
  2. Calculate the Age of a user upon giving their birthdate.
    I need to calculate the age of a user upon entering their birthdate in a form field in a CF Flash form. Birthdate: 01/01/1970 Age: ## (Age get generated.) Thanks
  3. Birthdate Popup
    Excell 2000 Ok, so I am trying to creat a pop up box to figure birthdates out whenever it comes needed, and i want it to exist in the personal workbook vba, so it will be in all workbooks, and when you press like Shift-Alt-B I want it to be a box that you type a date in, an...
  4. Convert birthdate to age
    Is there a way to convert a birthdate into months. I can convert it to years, thanks to you gurus, but can't find a way to convert a DOB to nonths for people less then a year.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: rrjegan17Posted on 2009-09-09 at 19:32:11ID: 25297041

Instead of:

and Age >= @AgeMin and Age<=@AgeMax

Replace with

and DATEDIFF(YY, Birthdate, getdate()) between @AgeMin and @AgeMax

 

by: CGLuttrellPosted on 2009-09-09 at 19:33:33ID: 25297045

Datediff(yyyy,getdate(),birthdate)

That will give num years diff aka Age.

 

by: rrjegan17Posted on 2009-09-09 at 19:33:55ID: 25297047

Above comment was assuming Birthdate as Datetime column.
If not convert it into Datetime and then do Datediff..

And note that this would tell the completed years and not the running years..
If you need it to be compared for running years, then Add 1 to make it work like

and DATEDIFF(YY, Birthdate, getdate()) + 1 between @AgeMin and @AgeMax

 

by: rrjegan17Posted on 2009-09-09 at 19:35:00ID: 25297049

CGLuttrell,
    Datediff(yyyy,getdate(),birthdate) would give age in negative values..
Startdate should be placed first and then enddate..

Hope you agree with this

 

by: aikimarkPosted on 2009-09-09 at 21:57:05ID: 25297469

Do you need the ages as of a certain date or just the current date?

How accurate do you need this age calculation?  (Day, Month, Year)

Is this SQL running in a stored proc?

==============
Note: I find the DateDiff() function to be a bit too simplistic to use for such calculations.  It simply subtracts the M or D or Y portion of two dates.  It isn't really giving you an AGE difference so much as it is giving you a year difference.  While the DateDiff() function would be accurate on the person's birthday, it would miss calculate the person's AGE on every day leading up to that person's birthday.

AGE calculation is a 'step function'.  You are a certain age, in years, until your birthday (birthdate anniversary), when you suddenly become one year older.

=================
Since I don't see this approach posted...you can convert the @AgeMin and @AgeMax to dates and compare them to the birthdate.  This would be much more efficient in a stored proc.

Where Birthdate Between 
 
CAST(CAST(Year(GetDate()) - @AgeMax AS varchar(4)) + '-' 
+ CAST(Month(GetDate()) AS varchar(2)) + '-' + CAST(Month(GetDate() AS varchar(2)) AS datetime)
 
And 
 
CAST(CAST(Year(GetDate()) - @AgeMin AS varchar(4)) + '-' 
+ CAST(Month(GetDate()) AS varchar(2)) + '-' + CAST(Month(GetDate() AS varchar(2)) AS datetime)

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

 

by: CGLuttrellPosted on 2009-09-10 at 00:22:23ID: 25297938

@rrjegan17,  I agree, was working quickly from mobile and got it backwards.

 

by: victoria_yPosted on 2009-09-10 at 02:32:57ID: 25298577

Here are 2 formulas I use to get the exact "age":

Not taking leap years into consideration (fine for most scenarios):
select cast(datediff(d, Birthdate, getdate()) AS DECIMAL (8,1))/365

Taking leap years into consideration (more precise):
select cast(datediff(d, Birthdate, getdate()) AS DECIMAL (8,1))/365.25

 

by: rrjegan17Posted on 2009-09-10 at 02:34:59ID: 25298585

bolenka,
   No responses from your end..

 

by: bolenkaPosted on 2009-09-10 at 04:45:47ID: 25299212

sorry...posted late last night...had to go to bed...I apologize...let me take a look at all responses this morning...and get back to you.

 

by: rrjegan17Posted on 2009-09-10 at 04:59:38ID: 25299289

Ok.. No Probs..
Waiting for your responses..

 

by: bolenkaPosted on 2009-09-10 at 05:24:05ID: 25299443

aikimark: I am reading your post, and am trying that one out, and so far it seems to work...but, so I am learning...what is the difference between what you posted and say, what victoria posted???

btw, I appreciate you putting all the code I would need for the where clause....there was a missing parentheses, but I figure it out no biggie.

thanks, to everyone...so so much...i am not quite done yet, but will let you know about points asap.

 

by: rrjegan17Posted on 2009-09-10 at 05:28:18ID: 25299469

bolenka,
   Have you read my comment at the beginning..

 

by: victoria_yPosted on 2009-09-10 at 05:33:47ID: 25299499

I think it depends on what you are comparing to for your parameters.  If your AgeMin and AgeMax are numbers (like you want everyone between 40 and 60 years old), you could use my code like so:

SELECT FirstName, LastName, City, [State], ZipCode, Comment, Birthdate 
FROM ProfilePreferences 
WHERE ZipCode 
IN( some other code here) 
and Gender=@Gender
and cast(datediff(d, Birthdate, getdate()) AS DECIMAL (8,1))/365 between @AgeMin and Age<=@AgeMax

                                              
1:
2:
3:
4:
5:
6:

Select allOpen in new window

 

by: bolenkaPosted on 2009-09-10 at 05:36:14ID: 25299514

yes, thank you rrjegan17, by running years, you mean like the date you are and then adding all extra days ...like, I turn 36 tomorrow, but I am not yet 36 today, but on my birthday tomorrow, I will be 36...right?

so that would be in the where clause as well??? I will try that also right now. Thanks so much.

 

by: bolenkaPosted on 2009-09-10 at 05:39:45ID: 25299533

right victoria: my age min and max are numbers...that is correct....because they are just being passed in from an aspx form...like

I want this data where the people I am looking for are between ages 18 (dropdownlist) and 32(dropdown list), but in the database, when they create their profile, I don't want them to have to enter in their age. The database stores the birthdate in a datetime field. So, that is why I want it to convert to age and compare the age to the birthdate...so I guess the birthdate would have to be converted to age for comparison, right?

 

by: rrjegan17Posted on 2009-09-10 at 05:43:10ID: 25299558

Yes.. you are correct..

Comment 25297041 is with completed years and 25297047 is with running year.
Just replace those lines in your actual query to make it work.

 

by: victoria_yPosted on 2009-09-10 at 05:45:17ID: 25299578

Bolenka,

Exactly.  I actually came up with this code originally when I had to show the age of buildings acquired on a report and all I had was the acquired date in the database.  I didn't want to see the results as something like 39 years and 4 months and 2 days.  I wanted to see the decimal equivalent, or 39.3388.  I think this works perfectly for your example, as well.

 

by: bolenkaPosted on 2009-09-10 at 05:48:11ID: 25299603

ok, i am still looking..then will award pts. thanks so much to everyone.

 

by: aikimarkPosted on 2009-09-10 at 05:48:17ID: 25299605

@Bolenka

You either convert the birthdate into an age (at a specific date) or you convert the (integer) min and max age to dates.  If this is a big table, a stored proc can initialize two date variables from the two age parameters, comparing each row's birthdate value without any more data conversions.  This should perform much faster than converting every row's birthdate value into an age.

 

by: bolenkaPosted on 2009-09-10 at 06:17:28ID: 25299830

aikimark: aha, gotcha. see...that is the stuff I dont know about...I really need to learn which sql queries have more/less impact on performace. Any general rules about this? Or is it too broad of a subject? thanks again.

 

by: aikimarkPosted on 2009-09-10 at 09:29:08ID: 25301830

I think too broad for this current discussion.  After we've solved your problem, open a new question to get direction and resources for performance-related questions.

 

by: bolenkaPosted on 2009-09-10 at 09:37:07ID: 25301907

ok thanks.

 

by: bolenkaPosted on 2009-09-25 at 17:12:03ID: 31626909

thanks to all...sorry it took so long...got busy and forgot to award points...thanks so much for your time.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...