MySQL Calculate Age
One of the most commonly performed date calculations is one which calculates age. Unfortunately there isn’t a function to do it, so we have to conjure it on our own.
The final mysql function to calculate age is the following:
SELECT YEAR(CURRENT_DATE()) – YEAR(’1971-12-31‘) – (RIGHT(CURRENT_DATE(),5)<’12-31‘) AS age;
where 1971-12-31 is the birth date and 12-31 is the birth month and day
Explanation:
The functions used in age calculation are:
- CURRENT_DATE() = Calculates the current date
————————
| CURRENT_DATE() |
———————–
| 2007-06-06 |
———————– - YEAR()= Returns Year from a given date
————————
| YEAR(’2007-09-15′) |
————————
| 2007 |
———————— - RIGHT()= Returns defined no of characters, starting from the right of the string
———————
| RIGHT(’abcdef’,2) |
———————
| ef |
——————— - MySQL evaluates a true expression to 1, and a false expression to 0.
For example:
SELECT 23>19;
———-
| 23>19 |
———-
| 1 |
———-
Now look at the MYSQL command again:
SELECT YEAR(CURRENT_DATE()) – YEAR(’1984-09-15′) – (RIGHT(CURRENT_DATE(),5)<’12-31′) AS age;
YEAR(CURRENT_DATE()) = Determines current year = 2007
YEAR(’1984-09-15′) = Determines the birth year = 1984
2007-1984=23 So the age is 23 years which is wrong as the person would not turn 23 till 15th of september and we assumed the current date to be 06-06-2007. The best way to do this is to compare whether the current month and day are larger than the birth month and day. If it is, a full year has passed, and the year portion of the calculation can be left. If it isn’t, a full year hasn’t passed, and you need to subtract one from the year portion. It sounds tricky, but it isn’t really.
RIGHT(CURRENT_DATE(),5) = Get the first five characters from the right side of the current date. 06-06 (as current date is 2007-06-06)
(’06-06′<’12-31′) = Is 6th of August less then 31st of December = yes = 1
So Finally you 23-1=22years which is the correct age.
Summary
Step1: SELECT YEAR(CURRENT_DATE()) – YEAR(’1984-09-15′) – (RIGHT(CURRENT_DATE(),5)<’12-31′) AS age;
Step2: SELECT 2007 - 1984 - (‘06-06‘<’12-31′) AS age;
Step3: SELECT 23 – 1 AS age;
Step4: 22
Note: If you are using the above function in a PHP webpage then add the mysql commands in mysql_query() php statement.
Eg: mysql_query(”SELECT YEAR(CURRENT_DATE()) – YEAR(’1971-12-31′) – (RIGHT(CURRENT_DATE(),5)<’12-31′) AS age”);
Reference: http://mysql-tips.blogspot.com/2005/04/mysql-date-calculations.html