Get Age from birthday in PostgreSQL – AGE()

In PostgreSQL, you can calculate the age from a birthday using the AGE() function. This function returns the interval between the current date and the given date (birthday). Let’s see how to

  • Get Age from Birthday in PostgreSQL using AGE() function.
  • Get age from Date of birth in year, month and days in PostgreSQL
  • Get age from Date of birth in years only in PostgreSQL
  • Calculate age till current date in years, month and days in PostgreSQL

 

Syntax of AGE() function in PostgreSQL:

AGE(timestamp, timestamp)

  • timestamp: The date or timestamp to calculate the age from.

When using the AGE() function, you can provide the current date (usually the CURRENT_DATE or NOW()) and the birthday to get the age.

 

Examples

Example 1: Calculating Age from a Fixed Date in PostgreSQL

To calculate the age from a specific birthday (e.g., 1990-03-01):

 

SELECT AGE('2024-06-28', '1990-03-01') AS age;

Output:

Get Age from birthday in PostgreSQL – AGE() 1

 

Example 2: Calculating Age from Current Date in PostgreSQL

To calculate the age from the current date:

 

SELECT AGE(CURRENT_DATE, '1990-03-01') AS age;

Output:

Get Age from birthday in PostgreSQL – AGE() 2

 

 

Example 3: Calculating Age till current date  from date of birth in a PostgreSQL Table

Get age from Date of birth in year month and days in PostgreSQL:

Suppose you have a table Student_detail with a column birthdaytime containing the birthdates of Students.

Get Age from birthday in PostgreSQL – AGE() 3

To calculate the age for each student, we will be using AGE() function and it will give us Age in Years, Months and Days

 

select *,age(CURRENT_DATE,date(birthdaytime)) as age from student_detail

Output:

Get Age from birthday in PostgreSQL – AGE() 4

 

 

Example 4: Extracting Age from date of birth in PostgreSQL in Years Only

If you want to extract the age in years only, we will be using AGE() function first and it will give us Age in Years, Months and Days, and then we will be extracting only year from it using DATE_PART() function.

 

SELECT *, DATE_PART('year', AGE(CURRENT_DATE, birthdaytime)) AS age_years FROM student_detail;

Output:

Get Age from birthday in PostgreSQL – AGE() 5

 

 

 

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts