Exclusion Adjacent Slots With btree_gist
Combine scalar equality with an integer-range operator in one EXCLUDE USING gist constraint so adjacent booking slots may touch but never overlap.
Code
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE court_slots (
slot_id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
court text NOT NULL,
minutes int4range NOT NULL,
-- btree_gist 让 court 的 = 与 range 的 && 组合进同一条 GiST 约束
EXCLUDE USING gist (court WITH =, minutes WITH &&)
);
-- 相邻时段(左开右闭)允许共存:600-660 与 660-720 端点相接不重叠
INSERT INTO court_slots (court, minutes) VALUES
('court-1', int4range(600, 660)),
('court-1', int4range(660, 720));
-- 重叠预约被约束当场拒绝
INSERT INTO court_slots (court, minutes) VALUES
('court-1', int4range(650, 710));
-- 不同场地互不影响
INSERT INTO court_slots (court, minutes) VALUES
('court-2', int4range(600, 660));
SELECT court, minutes::text FROM court_slots ORDER BY court, minutes;
DROP TABLE court_slots;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with court_slots among the objects involved.
Mechanically, the statements are built from: an ORDER BY that fixes the output order; 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.
Applying it
The court_slots table is the working surface here.
Statements that matter
CREATE TABLE court_slots (
slot_id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
court text NOT NULL,
minutes int4range NOT NULL,
EXCLUDE USING gist (court WITH =, minutes WITH &&)
);
INSERT INTO court_slots (court, minutes) VALUES
('court-1', int4range(600, 660)),
('court-1', int4range(660, 720));
INSERT INTO court_slots (court, minutes) VALUES
('court-1', int4range(650, 710));
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
- Which objects does the SQL touch?
- `court_slots`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.