RANGE_AGG And RANGE_INTERSECT_AGG Ranges
Merge group time windows into multiranges with range_agg and isolate shared overlap via range_intersect_agg across all rows in PostgreSQL.
Code
CREATE TEMP TABLE attendee_slots (
meeting text NOT NULL,
person text NOT NULL,
free_window tsrange NOT NULL
);
INSERT INTO attendee_slots VALUES
('kickoff', 'ada', '[2026-11-24 09:00, 2026-11-24 12:00)'),
('kickoff', 'ben', '[2026-11-24 10:00, 2026-11-24 13:00)'),
('kickoff', 'cyd', '[2026-11-24 11:00, 2026-11-24 14:00)'),
('retro', 'ada', '[2026-11-24 09:00, 2026-11-24 10:00)'),
('retro', 'ben', '[2026-11-24 10:00, 2026-11-24 11:00)'),
('retro', 'cyd', '[2026-11-24 13:00, 2026-11-24 14:00)');
-- range_agg merges overlapping/adjacent ranges into a multirange (PG 14+)
-- range_intersect_agg returns the overlap common to every row in the group (PG 15+)
SELECT
meeting,
range_agg(free_window)::text AS union_multirange,
range_intersect_agg(free_window)::text AS shared_window,
isempty(range_intersect_agg(free_window)) AS no_common_slot
FROM attendee_slots
GROUP BY meeting
ORDER BY meeting;Logic trace — RANGE_AGG And RANGE_INTERSECT_AGG Ranges
What runs here is SELECT / INSERT / CREATE — attendee_slots are the objects involved.
attendee_slots provisions temporary scratch storage inline within this query block so prior database state is unnecessary and cleanup happens automatically on close.
Concretely, the SQL combines: a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Using it
Nothing outside the file is needed: the session-local tables it touches (attendee_slots) are created by the file itself — point it at a scratch database and run the whole thing.
Key statements
SELECT
meeting,
range_agg(free_window)::text AS union_multirange,
range_intersect_agg(free_window)::text AS shared_window,
isempty(range_intersect_agg(free_window)) AS no_common_slot
FROM attendee_slots
GROUP BY meeting
ORDER BY meeting;
CREATE TEMP TABLE attendee_slots (
meeting text NOT NULL,
person text NOT NULL,
free_window tsrange NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which tables does this file reference?
- The references are `attendee_slots`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.