Range and multirange types
Overview
A range describes a set of values between bounds; a multirange stores ordered, nonempty, nonoverlapping and nonadjacent ranges. PostgreSQL supports native range and multirange types. This lesson uses integer half-open intervals [start,end) as a portable subset in SQLite, useful for bookings and availability.
First example
SELECT id FROM ct_interval WHERE start_n < 6 AND 4 < end_n ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1 ], [ 3 ], [ 4 ]]How it works
For nonempty bounded half-open intervals, A and B overlap exactly when A.start < B.end and B.start < A.end. Touching endpoints are adjacent, not overlapping. To merge intervals sorted by start, compare each start with the maximum prior end, not only the previous row end (nested intervals can hide longer ranges). A gap begins only when start > prior maximum end if adjacency should merge. Native PostgreSQL handles empty and unbounded ranges too; this fixture deliberately excludes them. A SELECT overlap check alone does not prevent concurrent overlapping inserts; exclusion constraints are taught in the next chapter.
Practical example
WITH prior AS ( SELECT *,MAX(end_n) OVER (ORDER BY start_n,end_n,id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prev_end FROM ct_interval), groups AS ( SELECT *,SUM(CASE WHEN prev_end IS NULL OR start_n>prev_end THEN 1 ELSE 0 END) OVER (ORDER BY start_n,end_n,id ROWS UNBOUNDED PRECEDING) AS grp FROM prior)SELECT MIN(start_n),MAX(end_n) FROM groups GROUP BY grp ORDER BY 1;Observed SQLite result (rows in JSON):
[ [ 1, 8 ], [ 10, 12 ]]Practice and mistakes
Practice: identify intervals overlapping [4,6). Hint 1: check both inequalities. Hint 2: do not use BETWEEN, which includes both endpoints. Expected IDs: 1, 3, 4. Then modify the merge query to treat touching intervals as separate by changing > to >=. Do not sum lengths of overlapping intervals before merging.
PostgreSQL 17 example — NOT RUN
SELECT int4range(1,5,'[)') && int4range(5,8,'[)') AS overlap, int4multirange(int4range(1,5),int4range(4,8),int4range(10,12))::text AS merged;Expected result, not executed: [[false, "{[1,8),[10,12)}"]]