Sub topic 9
Adding and Subtracting Dates and Timestamps
This chapter assumes basic SQL, including SELECT, WHERE, and GROUP BY, plus a general understanding of UTC and UTC offsets. The examples use PostgreSQL date and time types.
Choose the operation by the meaning
PostgreSQL supports arithmetic on date, timestamp, timestamptz, and interval values. An interval represents a length of time, such as three days or two months.
| Expression | Result | Meaning |
|---|---|---|
| `date + integer` | `date` | Add whole calendar days |
| `date - date` | `integer` | Count days between dates |
| `timestamp + interval` | `timestamp` | Move a wall-clock timestamp |
| `timestamptz + interval` | `timestamptz` | Move an instant through calendar or elapsed time |
A date has no time of day. Adding an integer to a date adds that many calendar days:
SELECT date '2024-06-01' + 7 AS next_week,
date '2024-06-01' - 7 AS previous_week,
date '2024-06-10' - date '2024-06-01' AS days_between;The results are 2024-06-08, 2024-05-25, and 9.
Adding an interval to a date produces a timestamp because the interval can contain hours or smaller units:
SELECT date '2024-06-01' + interval '2 days 4 hours'
AS scheduled_time;The result is 2024-06-03 04:00:00.
Add intervals to timestamps
Use an interval when the value represents a date and time:
SELECT timestamp '2024-06-01 09:30:00'
+ interval '90 minutes' AS later,
timestamp '2024-06-01 09:30:00'
- interval '1 day' AS yesterday;You can subtract two timestamps. The result is an interval:
SELECT timestamp '2024-06-03 12:00:00'
- timestamp '2024-06-01 09:30:00'
AS elapsed;The result is 2 days 03:00:00.
Intervals can combine units. PostgreSQL keeps calendar units such as months separate from time units such as hours.
SELECT timestamp '2024-01-31 10:00:00'
+ interval '1 month' AS next_month;For a shorter month, PostgreSQL adjusts the result to the last valid day. In leap year 2024, this produces 2024-02-29 10:00:00. This behavior is useful for many billing and calendar operations, but it means that repeatedly adding one month is not always the same as adding a fixed number of days.
Calendar time versus elapsed time
For timestamptz, a day interval follows calendar time in the active time zone. An interval of 24 hours follows elapsed time. These can differ when daylight saving time changes.
SET TimeZone = 'America/New_York';
SELECT TIMESTAMPTZ '2024-03-09 12:00:00'
+ interval '1 day' AS calendar_day,
TIMESTAMPTZ '2024-03-09 12:00:00'
+ interval '24 hours' AS elapsed_day;The first result is 2024-03-10 12:00:00-04. The second is 2024-03-10 13:00:00-04. The spring-forward change removes one local clock hour, so 24 elapsed hours reaches a later local time.
Exercise
Which expression should you use for a subscription that renews at the same local time every month: interval '720 hours' or interval '1 month'?
Show answer
Use interval '1 month'. A month is a calendar unit whose length varies, while 720 hours is a fixed elapsed duration.