I am trying to calculate how old is a person in a database.
Let\'s suppose to have this simple table:
student(id, birth_date);
Where
The accepted answer is almost correct, but can lead to wrong results.
In fact, / 365
doesn't take into consideration leap years, and can lead to falsy results if you compare a date that has the same day&month than the birthdate.
In order to be more accurate, you have to divide it by the average days in years for 4 years, aka (365 * 4) + 1 (the leap year every 4 years) => 365.25
And you will be more accurate :
select id, floor(datediff(curdate(),birth_date) / 365.25) from student
Tested for one of my project and it's working.
select id, floor(datediff(curdate(),birth_date) / 365)
from student
What about flooring the result to be an integer?
You can use this to get integer value.
select id, CAST(datediff(curdate(),birth_date) / 365 as int)
from student
If you want to read about CONVERT()
and CAST()
here is the link.