Tstzrange Overlap And Containment

Answer scheduling questions with tstzrange operators: && tests overlap, @> tests containment, and lower, upper, and upper_inc expose exact boundaries.

SqlData Integrity

Code

snippet
-- 范围类型把"时间段"当一等公民:操作符直接表达排期问题
-- && 重叠    @> 包含    <@ 被包含    -|- 相邻
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

FAQ

What are the relations in play here?
`existing`, `room_bookings` — referenced directly, no join needed.