CHECK Constraint Only Sees Its Row
CHECK evaluates each row in isolation — it cannot query other rows — so cross-row invariants need UNIQUE or exclusion constraints instead.
Code
-- GiST 对标量类型(如 bigint 的 =)没有默认操作符类,不装扩展直接建
-- EXCLUDE 会报 "data type bigint has no default operator class for
-- access method "gist""。btree_gist 把 btree 的等值比较接入 GiST。
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_reservations (
reservation_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id bigint NOT NULL REFERENCES rooms (room_id),
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL,
-- 行级不变量:只引用本行,CHECK 完全胜任
CONSTRAINT ends_after_starts CHECK (ends_at > starts_at),
-- 最短时长也是行级:一行内两个列的比较
CONSTRAINT at_least_one_hour CHECK (ends_at - starts_at >= interval '1 hour')
);
-- 同一 room_id 的两条预约可以落在同一时段:
-- CHECK 不看其他行,冲突与否取决于数据库实现,因此必须有跨行约束
ALTER TABLE room_reservations
ADD CONSTRAINT no_double_booking
EXCLUDE USING gist (
room_id WITH =,
tstzrange(starts_at, ends_at) WITH &&
);
-- 这一条被行级 CHECK 拦下:结束时间不晚于开始
INSERT INTO room_reservations (room_id, starts_at, ends_at)
VALUES (1, '2026-11-20 09:00+00', '2026-11-20 08:00+00');
-- 这一条通过行级 CHECK,但被跨行 EXCLUDE 拦下(与已存在的行重叠)
INSERT INTO room_reservations (room_id, starts_at, ends_at)
VALUES (1, '2026-11-20 09:30+00', '2026-11-20 11:00+00');How the snippet works
INSERT / CREATE / ALTER statements share the script, touching room_reservations.
Mechanically, the statements are built from: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value; a foreign-key REFERENCES guard that anchors child rows to the parent table.
Applying it
The room_reservations table is the working surface here.
Statements that matter
ALTER TABLE room_reservations
ADD CONSTRAINT no_double_booking
EXCLUDE USING gist (
room_id WITH =,
tstzrange(starts_at, ends_at) WITH &&
);
INSERT INTO room_reservations (room_id, starts_at, ends_at)
VALUES (1, '2026-11-20 09:00+00', '2026-11-20 08:00+00');
INSERT INTO room_reservations (room_id, starts_at, ends_at)
VALUES (1, '2026-11-20 09:30+00', '2026-11-20 11:00+00');
Interactive Tools for This Topic
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.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.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 relations are involved here?
- The references are `room_reservations`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.