Postgres age() function
Calculate the difference between timestamps or between a timestamp and the current date/time
The Postgres age()
function calculates the difference between two timestamps or the difference between a timestamp and the current date and time.
This function is particularly useful for calculating ages, durations, or time intervals in various applications. For example, you can use it to determine a person's age, calculate the time elapsed since an event, or find the duration of a process or subscription.
Function signatures
The age()
function has two forms:
This form produces an interval by subtracting the second timestamp from the first.
- First argument: The end timestamp
- Second argument: The start timestamp
This form subtracts the given timestamp from the timestamp for the current date (at midnight).
Example usage
Let's consider a table called employees
that stores employee information, including their birth dates. We can use the age()
function to calculate the age of employees.
This query calculates the age of each employee based on their birth date.
We can also use the age()
function with two timestamps to calculate the duration of employment for each employee:
This query calculates how long each employee has been with the company.
Advanced examples
age()
for time-based calculations
Use The age()
function can be useful for various time-based calculations. For example, consider a projects
table that tracks the start date and deadline for projects. We can use age()
to calculate project durations and remaining time:
This query calculates the total duration of each project and the time remaining until the deadline.
Extract specific units from age intervals
You can extract specific units of time (like years, months, or days) from the interval returned by the age()
function. Here's an example that breaks down the age into years, months, and days:
This query provides a detailed breakdown of each employee's age in years, months, and days.
Additional considerations
Negative intervals
The age()
function can return negative intervals if the end timestamp is earlier than the start timestamp. Be mindful of this when using age()
in calculations or comparisons.
Alternative functions
-
operator — Can be used to subtract two dates or timestamps, returning an interval. This is equivalent to using theage()
function with two timestamps.current_date
— Returns the current date (without the time component). Can be used with the-
operator to calculate an age or duration.
Resources
Last updated on