Sub topic 8
Working with intervals
An interval is PostgreSQL's type for a length of time, such as "3 days" or "2 hours 30 minutes". It differs from timestamp and timestamptz, which mark a point on the timeline. This chapter assumes you know the date and time types, the session TimeZone setting, and basic timestamptz behavior from earlier chapters. It covers how an interval is stored, how to write one, which arithmetic produces one, and where the units behave differently.
What an interval stores
An interval is not a single count of seconds. PostgreSQL keeps three separate fields:
- Months (years are stored as 12 months each).
- Days.
- Microseconds, which hold the hours, minutes, and seconds.
The fields are never converted into each other when the value is stored. interval '1 month' is one month and zero days. interval '36 hours' is 36 hours and zero days. A calendar has no fixed length for a month or a day, so PostgreSQL waits until you add the interval to a timestamp before deciding what the units mean.
Writing intervals
There are several ways to write an interval.
SELECT interval '1 year 2 months 3 days 04:05:06';
-- 1 year 2 mons 3 days 04:05:06
SELECT interval 'P1Y2M3DT4H5M6S'; -- ISO 8601 form, same value
SELECT make_interval(days => 3, hours => 2);
-- 3 days 02:00:00
SELECT interval '1 day' * 7; -- multiply by a number from a column or parameter
-- 7 daysUse make_interval or multiplication when the amount comes from a column or a parameter. Building a string such as (n || ' days')::interval works, but it is harder to read and easy to get wrong.
A bare number with no unit is read as seconds:
SELECT interval '5';
-- 00:00:05Always write the unit.
Signs apply per field, so mixed signs are kept as written:
SELECT interval '-1 day 2 hours';
-- -1 days +02:00:00The IntervalStyle setting controls how intervals are printed. The default is postgres. Setting it to iso_8601 makes output round-trip with ISO 8601 parsers:
SET IntervalStyle = 'iso_8601';
SELECT interval '1 day 2 hours';
-- P1DT2HArithmetic that produces and uses intervals
The result type of date arithmetic depends on the operand types, so check it before you rely on it.
| Expression | Result type | Notes |
|---|---|---|
| `timestamp - timestamp` | `interval` | Days and a time part, never months |
| `timestamptz - timestamptz` | `interval` | Same, measured in elapsed time |
| `date - date` | `integer` | Number of days |
| `date + integer` | `date` | Adds days |
| `date + interval` | `timestamp` | The result includes a time of day |
| `timestamp + interval` | `timestamp` | Wall-clock arithmetic |
| `timestamptz + interval` | `timestamptz` | Day and month fields use the session `TimeZone` |
| `interval * double precision` | `interval` | Fractions cascade into smaller units |
Subtracting two timestamps never returns months, because the length of a month varies:
SELECT TIMESTAMP '2024-03-01' - TIMESTAMP '2024-01-01';
-- 60 days
SELECT interval '1 hour' * 1.5;
-- 01:30:00
SELECT interval '1 day' * 1.5;
-- 1 day 12:00:00If you want a "years, months, days" difference such as an age, use age():
SELECT age(TIMESTAMP '2024-03-15', TIMESTAMP '2023-01-10');
-- 1 year 2 mons 5 daysage() works by calendar fields, so it is the right tool for a person's age. For measuring elapsed time, use plain subtraction.
Months, days, and hours behave differently
Because the fields stay separate, the same-looking amount of time can land on different instants.
Months clamp at month ends. Adding a month moves to the same day number in the next month. If that day does not exist, PostgreSQL uses the last day of the month:
SELECT date '2024-01-31' + interval '1 month' AS month_end_add;
-- 2024-02-29 00:00:00Order and grouping matter. Two one-month additions are not the same as one two-month addition:
SELECT (date '2024-01-31' + interval '1 month') + interval '1 month' AS stepwise,
date '2024-01-31' + interval '2 months' AS at_once;
-- stepwise: 2024-03-29 00:00:00
-- at_once: 2024-03-31 00:00:00Days follow the local calendar. Hours are exact. For timestamptz, the day field moves the local date and keeps the local clock time. The hour field adds exactly that much elapsed time. They differ only when a daylight saving change falls in between:
SET TimeZone = 'America/New_York';
SELECT TIMESTAMPTZ '2024-03-09 12:00:00' + interval '1 day' AS plus_one_day,
TIMESTAMPTZ '2024-03-09 12:00:00' + interval '24 hours' AS plus_24_hours;
-- plus_one_day: 2024-03-10 12:00:00-04
-- plus_24_hours: 2024-03-10 13:00:00-04The clocks in New York jumped forward on 2024-03-10, so that calendar day is only 23 hours long. Use '1 day' for "same time tomorrow" and '24 hours' for "exactly one day of elapsed time". Because timestamptz + interval reads the session TimeZone, the same query can return different instants in sessions with different settings.
Comparing intervals
To compare intervals, PostgreSQL converts them to a single number, treating a month as 30 days and a day as 24 hours. Two intervals can therefore be equal while adding different amounts to a timestamp:
SELECT interval '1 day' = interval '24 hours' AS day_vs_hours,
interval '1 month' = interval '30 days' AS month_vs_days;
-- day_vs_hours: true
-- month_vs_days: trueTreat this equality as a sorting convenience, not as a statement that the two values behave the same. Do not use = on intervals to decide whether two calculations are interchangeable.
Normalizing with justify functions
Fields are not converted unless you ask. Three functions do it explicitly:
SELECT justify_hours(interval '36 hours'); -- 1 day 12:00:00
SELECT justify_days(interval '35 days'); -- 1 mon 5 days
SELECT justify_interval(interval '1 mon -1 hour');
-- 29 days 23:00:00justify_hours turns each 24 hours into a day. justify_days turns each 30 days into a month. justify_interval does both and also fixes mixed signs. Use them only for display, because they bake in the 24-hour day and 30-day month assumptions, which are exactly what the previous section warned about.
Extracting from an interval
extract reads one stored field and does not roll smaller units into larger ones:
SELECT extract(hour FROM interval '36 hours') AS hours;
-- 36
SELECT extract(epoch FROM interval '1 day 2 hours') AS seconds;
-- 93600 (a numeric value in PostgreSQL 14 and later)For epoch, PostgreSQL counts a month as 30 days and a year as 365.25 days. It cannot know which calendar months you mean. To measure an exact duration between two instants, subtract the timestamptz values and take the epoch of the result, which contains only days and time.
Practical patterns
A rolling window uses an interval on the right-hand side of a half-open range:
SELECT name, starts_at
FROM event
WHERE starts_at >= now()
AND starts_at < now() + interval '7 days';Keep the arithmetic on the constant side. Writing starts_at - interval '7 days' < now() is equivalent but prevents an index on starts_at from being used in the usual way.
To get a duration in a fixed unit, extract from the epoch and divide:
SELECT extract(epoch FROM (TIMESTAMPTZ '2024-06-01 09:00:00+00'
- TIMESTAMPTZ '2024-06-01 07:30:00+00')) / 60 AS minutes;
-- 90Common errors
- Writing
interval '5'and expecting days. It means 5 seconds. - Using
'30 days'to mean "a month". Use'1 month'so month lengths and clamping are handled for you. - Using
'24 hours'to mean "tomorrow at the same time" in a zone with daylight saving. - Assuming
a + i - ireturnsawhenicontains months. Clamping loses information. - Relying on
justify_intervaloutput as if it were exact.
Exercise
The session TimeZone is 'America/New_York'. You run SELECT TIMESTAMPTZ '2024-11-02 12:00:00' + interval '1 day', TIMESTAMPTZ '2024-11-02 12:00:00' + interval '24 hours'; The clocks fall back on 2024-11-03. Which result is 2024-11-03 12:00 local time, and why?
Show answer
The first, with interval '1 day'. The day field moves the local calendar date and keeps the 12:00 clock time. The '24 hours' version adds exactly 24 elapsed hours. Because 2024-11-03 is 25 hours long in New York, it lands at 11:00 local time.
Exercise
What does SELECT (date '2024-03-31' + interval '1 month') + interval '1 month'; return, and how does it differ from SELECT date '2024-03-31' + interval '2 months';?
Show answer
The first returns 2024-05-30 00:00:00. March 31 plus one month clamps to April 30, and one more month gives May 30. The second returns 2024-05-31 00:00:00, because the two months are applied in one step from March 31.