Tstzrange Overlap And Containment
Answer scheduling questions with tstzrange operators: && tests overlap, @> tests containment, and lower, upper, and upper_inc expose exact boundaries.
Code
-- 范围类型把"时间段"当一等公民:操作符直接表达排期问题
-- && 重叠 @> 包含 <@ 被包含 -|- 相邻
WITH existing AS (
SELECT '[2026-11-14 09:00+00, 2026-11-14 11:00+00)'::tstzrange AS slot
)
SELECT
slot && '[2026-11-14 10:00+00, 2026-11-14 12:00+00)'::tstzrange AS overlaps_new,
slot && '[2026-11-14 11:00+00, 2026-11-14 12:00+00)'::tstzrange AS overlaps_after,
slot @> '[2026-11-14 09:30+00, 2026-11-14 10:30+00)'::tstzrange AS covers_inner,
lower(slot) AS starts_at,
upper(slot) AS ends_at,
upper_inc(slot) AS end_inclusive,
isempty(slot) AS empty
FROM existing;
-- 预订冲突检查:新时段与同房间既有时段重叠即拒绝
CREATE TABLE room_bookings (room text NOT NULL, slot tstzrange NOT NULL);
INSERT INTO room_bookings VALUES ('A', '[2026-11-14 09:00+00, 2026-11-14 11:00+00)');
SELECT room, slot
FROM room_bookings
WHERE room = 'A'
AND slot && '[2026-11-14 10:00+00, 2026-11-14 12:00+00)'::tstzrange;What the code does
SELECT / INSERT / CREATE statements share the script, touching existing and room_bookings.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause constraining which rows the statement operates on; NOT NULL qualifiers on the required columns.
Applying it
Run the statement against the existing table.
Statements that matter
SELECT room, slot
FROM room_bookings
WHERE room = 'A'
AND slot && '[2026-11-14 10:00+00, 2026-11-14 12:00+00)'::tstzrange;
INSERT INTO room_bookings VALUES ('A', '[2026-11-14 09:00+00, 2026-11-14 11:00+00)');
CREATE TABLE room_bookings (room text NOT NULL, slot tstzrange NOT NULL);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What are the relations in play here?
- `existing`, `room_bookings` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.