Home > Database > Mysql Tutorial > How to Calculate Age from a Date of Birth Using MySQL's TIMESTAMPDIFF()?

How to Calculate Age from a Date of Birth Using MySQL's TIMESTAMPDIFF()?

Patricia Arquette
Release: 2025-01-16 11:33:56
Original
866 people have browsed it

How to Calculate Age from a Date of Birth Using MySQL's TIMESTAMPDIFF()?

Determining Age in MySQL (InnoDB) Databases

Let's say you have a database table storing individual birthdates in "dd-mm-yyyy" format. Calculating age involves subtracting the birthdate from the current date, but this yields a date difference, not a readily usable age.

To get the age in years, employ the TIMESTAMPDIFF() function. This function computes the difference between two datetime expressions, providing the result in a chosen unit.

Function Syntax:

<code class="language-sql">TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2)</code>
Copy after login

Here's how to apply it to calculate age:

<code class="language-sql">SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age;</code>
Copy after login

This query subtracts the birthdate ('1970-02-01') from the current date (CURDATE()), returning the difference in years.

Illustrative Example:

With a birthdate of '1970-02-01' and the current date as '2023-02-01':

<code>TIMESTAMPDIFF(YEAR, '1970-02-01', '2023-02-01') = 53</code>
Copy after login

The calculated age is 53 years.

Important Consideration:

Ensure your birthdate column is a correctly formatted datetime or date type; TIMESTAMPDIFF() requires compatible data types.

The above is the detailed content of How to Calculate Age from a Date of Birth Using MySQL's TIMESTAMPDIFF()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template