I have a dob field in my MySQL table that's of type date
. Just a small, trivial example is something like this:
mysql> select dob from players limit 5;
+------------+
| dob |
+------------+
| 1983-12-02 |
| 1979-01-01 |
| 1989-05-11 |
| 1976-03-24 |
| 1989-09-12 |
+------------+
I am trying to calculate ages with decimal points by using today's date. So technically if your birthday is June 1, 1981 or 1981-06-01, that makes you 33 and today is June 7.. you'd be 33.(6/365) or 33.02 years old.
What's the easiest way to calculate this using SQL?
Age can be expressed as decimal number, given that we keep in mind that it's not a normal decimal number during the whole calculatation.
Simply by subtracting the birth date from the current date. This conventional age formula can also be used in Excel. The first part of the formula (TODAY()-B2) returns the difference between the current date and date of birth is days, and then you divide that number by 365 to get the numbers of years.
The method of calculating age involves the comparison of a person's date of birth with the date on which the age needs to be calculated. The date of birth is subtracted from the given date, which gives the age of the person. Age = Given date - Date of birth.
Usually DOB calculation is pretty easy in mysql when you want to calculate the years without any fraction something as
mysql> select timestampdiff(YEAR,'1981-06-01',now());
+----------------------------------------+
| timestampdiff(YEAR,'1981-06-01',now()) |
+----------------------------------------+
| 33 |
+----------------------------------------+
But since you need the fraction also then this should do the trick
mysql> select format(datediff(curdate(),'1981-06-01') / 365.25,2);
+-----------------------------------------------------+
| format(datediff(curdate(),'1981-06-01') / 365.25,2) |
+-----------------------------------------------------+
| 33.02 |
+-----------------------------------------------------+
Year is considered as 365.25 days.
So in your case you may have the query as
select
format(datediff(curdate(),dob) / 365.25,2) as dob
from players limit 5;
You can use the to_days
function to calculate the days between the year zero and someone's birthday. Then subtract from today that number of days. That should give you the birthday as if someone was born in the year zero:
select year(subdate(now(), to_days(dob)))
Example at SQL Fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With