Calculating Age form birth day in SQL

trying to use one line convert DOB to age but getting floats, any way to get ride of floats?

DATEDIFF(day, birthdate, GetDate())) / 365.25 as AGE,

image

cast result to an integer:

select cast(datediff(...) as int)

Not an accurate calc all the time, could be a year off.

Tried but the same?

CAST(DATEDIFF(day, birthdate, GetDate()) as int) / 365.25 as AGE,

Birthday field is VARCHAR(10)

This is going to cause a lot of problems - you really should store dates and either DATE or DATETIME data types. And this calculation is not accurate and will return invalid age depending on the current date and the birth date.

This is a more accurate calculation if you just want the person's age - and not a fractional age:

datediff(year, cast(birthdate As datetime), getdate()) - 
        Case When getdate() < dateadd(year, datediff(year, cast(birthdate As datetime), getdate()), getdate())
             Then 1
             Else 0
         End

Now - if you really want to use the above calculation (which will be incorrect at times):

CAST(DATEDIFF(day, CAST(birthdate AS datetime), getdate()) / 365.25 AS int) AS AGE,

OK Thanks Jeff. I 'll use the

datediff(year, cast(birthdate As datetime), getdate()) -
Case When getdate() < dateadd(year, datediff(year, cast(birthdate As datetime), getdate()), getdate())
Then 1
Else 0
End
for now.

Please put that in a function. Performance issues are negligible.

So you have said before. Its not my experience, nor that of people who I respect who have posted their results and finding in articles and blogs.

1 Like

You are wrong. They are wrong.

I proved to you that your test was in error.

Only for small rowsets. (or are you just joking?) This is a well-known issue in SQL Server.

OK -- be sure you test with millions of rows. post your reproducible timings using a function and using an inline expression.

You are writing code that is difficult to maintain. Please use functions.

IF there is a performance problem with a particular query, you will be hired to cut and paste the code.

functions are fine as long as they are not executed on every row. In that case, forget it. they are provably abysmal.

1 Like

Computer cycles are cheap. Yours are not.

The human brain can hold a finite # of items in short term memory. Your productivity will increase by reducing complexity into functions.

Make it readable and maintainable. The vast majority of code doesn't need perfect optimization. IF something is a performance problem, users will complain and you can fix it with a simple cut and paste. You'll look like a hero.

Use functions please.