Sub topic 14
Generating Time Series and Using Range Types
This chapter assumes basic SQL, SELECT, joins, grouping, and PostgreSQL timestamp types. It also assumes you understand that timestamptz represents an instant, while a time zone controls how that instant is displayed.
Generate a series of times
generate_series is a PostgreSQL set-returning function. It produces one row for each value in a sequence. For time data, give it a start timestamp, an end timestamp, and an interval step.
SELECT tick
FROM generate_series(
TIMESTAMPTZ '2024-06-01 00:00:00+00',
TIMESTAMPTZ '2024-06-01 06:00:00+00',
INTERVAL '2 hours'
) AS series(tick);The result contains seven timestamps: midnight, 02:00, 04:00, and so on through 06:00. The stop value is included when the next step lands exactly on it.
You can use a generated series as a calendar or reporting scaffold. This keeps periods with no events in the result.
WITH hours AS (
SELECT hour_start
FROM generate_series(
TIMESTAMPTZ '2024-06-01 00:00:00+00',
TIMESTAMPTZ '2024-06-01 05:00:00+00',
INTERVAL '1 hour'
) AS series(hour_start)
)
SELECT h.hour_start, count(e.id) AS event_count
FROM hours AS h
LEFT JOIN event AS e
ON e.starts_at >= h.hour_start
AND e.starts_at < h.hour_start + INTERVAL '1 hour'
GROUP BY h.hour_start
ORDER BY h.hour_start;The half-open join includes the start and excludes the end. Therefore, an event exactly at 01:00 belongs to the 01:00 bucket, not both adjacent buckets.
Represent periods with range types
A range is one value containing a lower bound and an upper bound. PostgreSQL includes built-in range types for common temporal data.
| Range type | Element type | Typical use |
|---|---|---|
| `daterange` | `date` | Calendar dates |
| `tsrange` | `timestamp` | Local or zone-free periods |
| `tstzrange` | `timestamptz` | Real-world instants |
The usual notation [) means “lower bound included, upper bound excluded.” This matches half-open filtering.
CREATE TABLE room_booking (
room_id integer NOT NULL,
period tstzrange NOT NULL,
CHECK (NOT isempty(period))
);
INSERT INTO room_booking (room_id, period)
VALUES (
7,
tstzrange(
TIMESTAMPTZ '2024-06-01 09:00:00+00',
TIMESTAMPTZ '2024-06-01 10:00:00+00',
'[)'
)
);
SELECT room_id, period
FROM room_booking
WHERE period @> TIMESTAMPTZ '2024-06-01 09:30:00+00';The @> operator asks whether the range contains a value. The && operator asks whether two ranges overlap.
SELECT *
FROM room_booking
WHERE period && tstzrange(
TIMESTAMPTZ '2024-06-01 09:45:00+00',
TIMESTAMPTZ '2024-06-01 11:00:00+00',
'[)'
);For larger tables, add a GiST index. It allows PostgreSQL to find matching ranges without scanning every row.
CREATE INDEX room_booking_period_gist
ON room_booking USING gist (period);A range does not automatically prevent overlapping bookings. To enforce that rule, use an exclusion constraint.
ALTER TABLE room_booking
ADD CONSTRAINT room_booking_no_overlap
EXCLUDE USING gist (
room_id WITH =,
period WITH &&
);This rejects two rows for the same room whose periods overlap, while allowing adjacent periods such as [09:00, 10:00) and [10:00, 11:00).
Exercise
Which operator tests whether a tstzrange overlaps another range, and why are [) bounds useful?
Show answer
Use &&. [) includes the start and excludes the end, so adjacent periods do not overlap and boundary values are counted once.