Exclusion Constraint No Overlap

Enforce no-overlap booking with an EXCLUDE USING gist constraint: btree_gist combines room equality with range && so conflicting inserts are rejected.

SqlData Integrity

Code

snippet
-- 排斥约束(exclusion constraint)给出 no-overlap 保证:
-- btree_gist 扩展让 text 的 = 与 range 的 &&(overlap)可组合进 GiST 索引
CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TABLE room_bookings (
  booking_id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  room       text      NOT NULL,
  stays      tstzrange NOT NULL,
  EXCLUDE USING gist (room WITH =, stays WITH &&)
);

INSERT INTO room_bookings (room, stays)
VALUES ('skyline', '[2026-11-11 09:00, 2026-11-11 11:00)');

-- 与已有预约 overlap:被约束当场拒绝
INSERT INTO room_bookings (room, stays)
VALUES ('skyline', '[2026-11-11 10:00, 2026-11-11 12:00)');

-- 相邻不重叠(前一段右开):允许
INSERT INTO room_bookings (room, stays)
VALUES ('skyline', '[2026-11-11 11:00, 2026-11-11 13:00)');

How it works

Several statements share this file — INSERT / CREATE, with room_bookings among the objects involved.

Mechanically, the statements are built from: NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

Run it in the room_bookings database context.

Core lines

CREATE TABLE room_bookings (
booking_id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
room       text      NOT NULL,
stays      tstzrange NOT NULL,
EXCLUDE USING gist (room WITH =, stays WITH &&)
);
INSERT INTO room_bookings (room, stays)
VALUES ('skyline', '[2026-11-11 09:00, 2026-11-11 11:00)');
INSERT INTO room_bookings (room, stays)
VALUES ('skyline', '[2026-11-11 10:00, 2026-11-11 12:00)');

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`room_bookings` — referenced directly, no join needed.