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.
Code
-- 排斥约束(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
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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Name the tables involved in this file.
- `room_bookings` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.