Home > Database > Mysql Tutorial > How to Calculate Age from a Date of Birth Using MySQL?

How to Calculate Age from a Date of Birth Using MySQL?

Mary-Kate Olsen
Release: 2025-01-16 11:53:58
Original
973 people have browsed it

How to Calculate Age from a Date of Birth Using MySQL?

Use MySQL (InnoDB) to calculate age

This article describes how to use MySQL's TIMESTAMPDIFF function to calculate age based on the date of birth stored in the database.

Question:

Assuming the date of birth is stored in 'dd-mm-yyyy' format, we need to determine:

  • The format of the date returned after subtracting the dates.
  • How to calculate a person's age using the returned format.

Solution:

Date format:

The date format returned by MySQL after subtracting another date from the current date is the default MySQL date and time format: YYYY-MM-DD HH:MM:SS.

Calculate age:

We can use the TIMESTAMPDIFF function to calculate the difference between two dates in different units (including years). An example is as follows:

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

This query calculates the difference between February 1, 1970 and the current date and returns the age in years.

Example:

Consider a table containing a column called 'date_of_birth' in the format 'dd-mm-yyyy':

<code class="language-sql">CREATE TABLE persons (
  id INT PRIMARY KEY,
  name VARCHAR(255),
  date_of_birth DATE
);

INSERT INTO persons (name, date_of_birth) VALUES
  ('John Doe', '1970-02-01'),
  ('Jane Doe', '1975-04-15');</code>
Copy after login

To calculate 'John Doe's' age we will run the following query:

<code class="language-sql">SELECT TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) AS age
FROM persons
WHERE name = 'John Doe';</code>
Copy after login

This query will return results:

<code>age
51</code>
Copy after login

The above is the detailed content of How to Calculate Age from a Date of Birth Using MySQL?. 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