How can I calculate age from date of birth in SQL?

1.2K    Asked by AshishSinha in SQL Server , Asked on Dec 14, 2023

I am tasked with developing a database for a system like healthcare that can store the information of patients, including their date of birth. How can I construct an SQL query for calculating the present age of every patient based on their date of birth? 

Answered by Charles Parr

 In the context of SQL, to calculate age from date of birth in SQL, you can easily go with the DATEIFF() function. However, there are also some other functions available in different database systems such as MySQL, PostgreSQL, etc.

Here is the example given by using the data server MySQL:-

    Patient_id,featurestefeaturesth,
    STAMPDYEAR, dte_ofbirth, CURDATE()) AAIage from
    Patients_table;

This above SQL query will calculate the age, of patients by finding the difference in years between the “date of birth” column and the current date. Then the “TIMMPDI” function showcases the result of the age in years.

You can replace “patients _ name” and “patients_ Id” with your real name and ID of your patients.

In the SQL server, the method is a little bit different

SELECT 
    Patient_id,
    Date_of_birth,
    DATEDIFF(YEAR, date_of_birth, GETDATE()) AS age
FROM
   A Patients_table;

In the SQL server, the GETDATE() function helps in providing the current date in the SQL server.



Your Answer

Interviews

Parent Categories