Home > Database > Mysql Tutorial > How Can I Calculate Age from a Date of Birth Using SQL?

How Can I Calculate Age from a Date of Birth Using SQL?

Patricia Arquette
Release: 2025-01-22 13:37:09
Original
1000 people have browsed it

How Can I Calculate Age from a Date of Birth Using SQL?

Use DATE and GETDATE() functions in SQL to calculate age

In database tables containing personal information, it is often useful to determine the age of an individual. This requires converting the provided date of birth (DOB) into a usable format and calculating the elapsed years.

In order to convert a DOB string into a recognized date format, we can use the CAST() function:

<code class="language-sql">SELECT CAST(DOB AS DATE) FROM YourTable;</code>
Copy after login

Once the DOB is in the desired date format, we can use the GETDATE() function to retrieve the current date and time:

<code class="language-sql">SELECT GETDATE();</code>
Copy after login

Now we can calculate age by subtracting the DOB from the current date and dividing the result by the number of milliseconds in the year:

<code class="language-sql">SELECT DATEDIFF(YEAR, DOB, GETDATE()) AS Age</code>
Copy after login

Alternatively, if you prefer greater precision, you can use the following formula:

<code class="language-sql">SELECT ROUND((JULIANDAY(GETDATE()) - JULIANDAY(DOB)) / 365.25, 2) AS AgeDecimals</code>
Copy after login

This formula takes into account leap years and provides the age in decimal years.

To get the full picture, we can add age information to the existing table data:

<code class="language-sql">SELECT ID, Name, DATEDIFF(YEAR, DOB, GETDATE()) AS Age
FROM YourTable;</code>
Copy after login

The output will contain age values ​​along with other personal information, providing a more complete record for each individual.

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