Sub topic 14
Generating time series and using range types
This chapter covers two tools for working with spans of time. generate_series produces a row for every step between two points. Range types store a start and an end as one value. It assumes you can already convert zones with AT TIME ZONE, do interval arithmetic, and write half-open (>= start, < end) range queries. The event table is the one from earlier chapters.
Generating a series of timestamps
generate_series(start, stop, step) returns one row per step, beginning at start. It includes stop if a step lands on it exactly.
SET TimeZone = 'UTC';
SELECT generate_series(
TIMESTAMPTZ '2024-06-01 00:00:00+00',
TIMESTAMPTZ '2024-06-01 03:00:00+00',
interval '1 hour'
) AS hour_start;
-- 2024-06-01 00:00:00+00
-- 2024-06-01 01:00:00+00
-- 2024-06-01 02:00:00+00
-- 2024-06-01 03:00:00+00The step can be any interval, including '1 month' or '1 day'. The result type follows the input type. timestamptz inputs give timestamptz rows, and timestamp inputs give timestamp rows.
Day steps depend on the session zone
For timestamptz, a '1 day' step is applied in the session TimeZone. Each row keeps the same local clock time, as + interval '1 day' does. Across a daylight saving change, the rows stay at local midnight even though one day is only 23 hours long.
SET TimeZone = 'America/New_York';
SELECT generate_series(
TIMESTAMPTZ '2024-03-09 00:00:00',
TIMESTAMPTZ '2024-03-12 00:00:00',
interval '1 day'
) AS local_midnight;
-- 2024-03-09 00:00:00-05
-- 2024-03-10 00:00:00-05
-- 2024-03-11 00:00:00-04
-- 2024-03-12 00:00:00-04With interval '24 hours' the rows would drift to 01:00 after the change, because hours are elapsed time.
PostgreSQL 16 and later accept an optional fourth argument that names the zone for the stepping. This lets you avoid depending on the session setting:
SELECT generate_series(
TIMESTAMPTZ '2024-03-09 00:00:00-05',
TIMESTAMPTZ '2024-03-12 00:00:00-04',
interval '1 day',
'America/New_York'
) AS local_midnight;A common surprise with dates
Passing date values to generate_series returns timestamptz, because PostgreSQL resolves the call to the timestamptz version. The rows are then midnight in the session zone, which may not be what you meant. Pass timestamp literals, or cast the result:
SELECT g::date AS day
FROM generate_series(date '2024-06-01', date '2024-06-03', interval '1 day') AS g;
-- 2024-06-01
-- 2024-06-02
-- 2024-06-03Filling gaps in grouped data
A GROUP BY query returns only the days that have rows. To report days with zero events, generate every local day and LEFT JOIN the data onto it.
SELECT g.d::date AS local_day,
count(e.id) AS events
FROM generate_series(
timestamp '2024-06-01',
timestamp '2024-06-07',
interval '1 day'
) AS g(d)
LEFT JOIN event e
ON e.starts_at >= g.d AT TIME ZONE 'America/New_York'
AND e.starts_at < (g.d + interval '1 day') AT TIME ZONE 'America/New_York'
GROUP BY g.d
ORDER BY g.d;The series is made of plain timestamp values, which represent local calendar days. AT TIME ZONE turns each boundary into a real instant. The join condition is a half-open range on the raw starts_at column, so an index on starts_at can still be used. Use count(e.id), not count(*), so a day with no matching row counts 0 instead of 1.
Range types
A range type stores a lower and an upper bound in one value. PostgreSQL has built-in ranges for time:
| Type | Element type | Use for |
|---|---|---|
| `daterange` | `date` | Whole calendar days |
| `tsrange` | `timestamp` | Local wall-clock spans with no zone |
| `tstzrange` | `timestamptz` | Real instants, such as bookings and validity periods |
For absolute moments, use tstzrange. It carries the same instant semantics as timestamptz, and it prints in the session zone.
Bounds and canonical form
A range literal or constructor has inclusive ([, ]) or exclusive ((, )) bounds. The default is [), which is lower inclusive and upper exclusive. That matches the half-open convention from the previous chapter.
SET TimeZone = 'UTC';
SELECT tstzrange('2024-06-01 09:00+00', '2024-06-01 10:00+00');
-- ["2024-06-01 09:00:00+00","2024-06-01 10:00:00+00")
SELECT daterange('2024-06-01', '2024-06-03', '[]');
-- [2024-06-01,2024-06-04)daterange is a discrete range, because dates have a next value. PostgreSQL rewrites it into canonical [) form, so the inclusive end 2024-06-03 became the exclusive end 2024-06-04. tstzrange is continuous, so it keeps whatever bounds you give it.
A NULL bound means unbounded, which is useful for "valid from now on":
SELECT tstzrange(TIMESTAMPTZ '2024-06-01 00:00:00+00', NULL) @> TIMESTAMPTZ '2030-01-01 00:00:00+00';
-- trueOperators and functions
The operators you will use most:
@>tests whether a range contains a value or another range.<@is the reverse.&&tests whether two ranges overlap.-|-tests whether two ranges are adjacent.lower(r),upper(r),isempty(r),lower_inf(r)andupper_inf(r)inspect a range.*is intersection,+is union, and-is difference.+raises an error if the result would not be a single range.
SELECT upper(r) - lower(r) AS duration
FROM (SELECT tstzrange('2024-06-01 09:00+00', '2024-06-01 10:30+00') AS r) s;
-- 01:30:00Preventing overlaps with an exclusion constraint
Ranges let the database enforce rules such as "a room cannot be double-booked". A unique constraint cannot express overlap, but an exclusion constraint can. For a mix of equality on room_id and overlap on the range, you need the btree_gist extension. It lets a GiST index handle plain = comparisons.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE booking (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id int NOT NULL,
during tstzrange NOT NULL,
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
INSERT INTO booking (room_id, during)
VALUES (1, tstzrange('2024-06-01 09:00+00', '2024-06-01 10:00+00'));
-- Fails: overlaps the first booking in room 1
INSERT INTO booking (room_id, during)
VALUES (1, tstzrange('2024-06-01 09:30+00', '2024-06-01 10:30+00'));
-- ERROR: conflicting key value violates exclusion constraint
-- Succeeds: starts exactly when the first one ends
INSERT INTO booking (room_id, during)
VALUES (1, tstzrange('2024-06-01 10:00+00', '2024-06-01 11:00+00'));The third insert works because the first range excludes its upper bound, so the two ranges do not overlap. The constraint also builds a GiST index, which speeds up && and @> queries on during.
Bucketing with generated ranges
You can combine both tools. Generate a range for each bucket, then join on containment:
SELECT lower(b.bucket) AS bucket_start,
count(e.id) AS events
FROM (
SELECT tstzrange(d, d + interval '1 hour') AS bucket
FROM generate_series(
TIMESTAMPTZ '2024-06-01 00:00:00+00',
TIMESTAMPTZ '2024-06-01 05:00:00+00',
interval '1 hour'
) AS d
) b
LEFT JOIN event e ON b.bucket @> e.starts_at
GROUP BY b.bucket
ORDER BY lower(b.bucket);Because each bucket is [), an event at exactly 02:00 lands only in the 02:00 bucket.
Common errors
- Using
tsrangefor instants. Atsrangehas no zone, so@>with atimestamptzvalue casts using the session zone. The answer then changes withTimeZone. Usetstzrangefor real moments. - Expecting
[]to survive ontstzrange. It does survive for continuous types. It does not fordaterange, which canonicalizes. Compare ranges rather than reading the printed bounds. - Reading the series type wrongly. A
dateinput givestimestamptzrows, as covered above. - Forgetting that the stop value is included.
generate_serieswith an hourly step from 00:00 to 03:00 returns four rows, not three. - Missing
btree_gist.EXCLUDE USING gist (room_id WITH =, ...)fails with an operator class error if the extension is not installed. - Overlapping bookings that touch. If your business rule treats back-to-back bookings as conflicting, add a buffer or use a different rule. The default half-open range allows them.
Exercise
A table shift(id, worker_id int, during tstzrange) must never hold two overlapping shifts for the same worker, but back-to-back shifts such as 08:00-16:00 and 16:00-23:00 must be allowed. Write the constraint, and say why the second shift is accepted.
Show answer
Install btree_gist, then add EXCLUDE USING gist (worker_id WITH =, during WITH &&). The constraint is: CREATE EXTENSION IF NOT EXISTS btree_gist; ALTER TABLE shift ADD EXCLUDE USING gist (worker_id WITH =, during WITH &&);. The 16:00-23:00 shift is accepted because ranges built with the default [) bounds exclude their upper bound. The first shift ends just before 16:00, so && returns false for the two ranges.
Exercise
In the session zone America/New_York, you run generate_series(TIMESTAMPTZ '2024-03-09 00:00:00', TIMESTAMPTZ '2024-03-12 00:00:00', interval '24 hours'). How does the output differ from the '1 day' version, and why?
Show answer
The 24-hour version returns 2024-03-09 00:00-05, 2024-03-10 00:00-05, 2024-03-11 01:00-04, and 2024-03-12 01:00-04. Hours are elapsed time, so the 23-hour day on March 10 pushes later rows to 01:00 local time. A '1 day' step keeps local midnight.