Logo

How to Calculate Age From Date of Birth Using MySQL?

AuthorSumit Sarkar

Date25 Oct 2024

CategoryMySQL

In this tutorial, we will learn how to calculate age from date of birth using MySQL.

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 the DATEDIFF() function with FLOOR() and STR_TO_DATE() to correctly determine age without storing it in the database.
Comments 16

Leave a comment

Create Resume for free

Create a professional quality resume in minutes with free templates.

Create Resume
Resumes