Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Age in MySQL (InnoDb)

Tags:

sql

mysql

If I have a persons date of birth stored in a table in the form dd-mm-yyyy and I subtract it from the current date, what format is the date returned in?

How can I use this returned format to calculate someone's age?

like image 392
user559142 Avatar asked Apr 24 '11 21:04

user559142


People also ask

How do I calculate age in MySQL?

Retrieve the Age of Patients In MySQL, you can use the inbuilt TIMESTAMPDIFF() function to compute the difference between two dates and return a value either in days, months or years.

How does MySQL calculate duration?

To calculate the difference between the timestamps in MySQL, use the TIMESTAMPDIFF(unit, start, end) function. The unit argument can be MICROSECOND , SECOND , MINUTE , HOUR , DAY , WEEK , MONTH , QUARTER , or YEAR . To get the difference in seconds as we have done here, choose SECOND .

How do I calculate age in SQL using Sysdate?

SELECT ROUND((SYSDATE - TO_DATE('12-MAY-16'))/365.25, 5) AS AGE from DUAL; You can configure ROUND to show as many decimal places as you wish. Placing the date in decimal format like aforementioned helps with calculations of age groups, etc. This is just a contrived example.


1 Answers

You can use TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2) function:

SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age 

Demo

like image 150
Glavić Avatar answered Oct 05 '22 23:10

Glavić