Oct162007
Calculating Age In SQL
Goog Feed, General, SQL
Comments (3)
So, I was building an application at work that required me to know the age of an individual before further processing could be done on the record.
I thought this would be a piece of cake with the "dateDiff(yy,date1,date2)" function. That only gives the year difference. For instance if today's date is 10/16/2007 and you we're born on 10/17/1981, the dateDiff function would tell you that you're 26 years old when in fact you don't turn 26 till tomorrow.
This became problematic for me because I needed to know to the day how old this individual was at any given moment.
After a bit of browsing and small modifications on my end here is what I ended up using.
What the above SQL statement does is first grab the year difference. Then the CASE statement takes the month multiplied by 100 and adds the day of the date to that total. It also does the same thing for the second date passed in. It then evaluates the two and either leaves the year alone or subtracts one from it.
For this example I hard-coded the date of "10/15/1981" into the statement, but in my real-life example that became a sub-query based on an ID. Hope you find this as useful as I did.

Cheers