In MariaDB, you can use the TIMESTAMPDIFF()
function to calculate a person’s age (or the age of anything for that matter).
TIMESTAMPDIFF()
is a built-in date and time function that returns the difference between two date or datetime expressions. Passing YEAR
as the first argument, date of birth as the second argument, and the current date as the third, will return the age in years.
Example
Here’s an example to demonstrate:
SELECT TIMESTAMPDIFF(YEAR, '1985-02-15', CURDATE()) AS Age;
Result:
+------+ | Age | +------+ | 36 | +------+
Here, we use CURDATE()
to return the current date.
Database Example
Here’s an example that returns the age of pets in a database, then sorts the results by age in descending order:
SELECT
PetName,
DOB,
CURDATE(),
TIMESTAMPDIFF(YEAR, DOB, CURDATE()) AS Age
FROM Pets
ORDER BY Age DESC;
Result:
+---------+------------+------------+------+ | PetName | DOB | CURDATE() | Age | +---------+------------+------------+------+ | Scratch | 2018-10-01 | 2021-05-30 | 2 | | Fetch | 2019-08-16 | 2021-05-30 | 1 | | Wag | 2020-03-15 | 2021-05-30 | 1 | | Fluffy | 2020-11-20 | 2021-05-30 | 0 | | Tweet | 2020-11-28 | 2021-05-30 | 0 | | Fluffy | 2020-09-17 | 2021-05-30 | 0 | | Bark | NULL | 2021-05-30 | NULL | | Meow | NULL | 2021-05-30 | NULL | +---------+------------+------------+------+
Pets that are less than a year old have an age of 0
.
Where the date of birth column is null
, the result is null
.