In this tutorial, we will learn how to calculate age from date of birth using MySQL.
We can calculate age from date of birth using PHP, Laravel, CodeIgniter, etc. but in this we focus on how to calculate age using SQL Server’s DATEDIFF()
function.
Syntax
DATEDIFF(interval, date1, date2)
Example
SELECT
Id,
FLOOR(DATEDIFF(CURDATE(), STR_TO_DATE(born_date, '%Y-%m-%d')) / 365) AS age
FROM
`users`;
Parameter | Value/Description |
---|---|
Id | Column that holds the unique identifier for each user. |
born_date | Column that stores the user's date of birth, assumed to be in the format YYYY-MM-DD. |
CURDATE() | MySQL function that returns the current date (used to calculate age). |
STR_TO_DATE() | MySQL function that converts a string into a date, using the format specified (%Y-%m-%d). |
DATEDIFF() | MySQL function that calculates the difference in days between two dates. |
FLOOR() | MySQL function that rounds down the age calculation to the nearest whole number. |
Conclusion
Age can be calculated from a date of birth in MySQL using theDATEDIFF()
function withFLOOR()
andSTR_TO_DATE()
to correctly determine age without storing it in the database.
Leave a comment