PostgreSQL AGE() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL AGE()
function to calculate ages.
Introduction to PostgreSQL AGE() function
In business applications, you often have to calculate ages such as the ages of employees, and years of service of employees. In PostgreSQL, you can use the AGE()
function to accomplish these tasks.
Here’s the basic syntax of the AGE()
function:
The AGE()
function accepts two TIMESTAMP
values. It subtracts the second argument from the first one and returns an interval as a result.
For example:
Output:
If you want to use the current date as the first argument, you can use the following form of the AGE()
function:
For example, if someone’s birth date is 2000-01-01
, and the current date is 2024-01-26
, their age would be:
Output:
PostgreSQL AGE() function example
We’ll use the following rental
table in the sample database:
The following example uses the AGE()
function to retrieve the top 10 rentals that have the longest durations:
Output:
In this example, we use the AGE()
function to calculate the rental duration based on the values of the rental_date
and return_date
columns.
Summary
- Use the PostgreSQL
AGE()
function to calculate ages.