Partial Exclusion Constraint Ignores Old Rows

Scope an exclusion constraint with WHERE so cancelled bookings stop blocking new ones while active overlaps still fail.

SqlData Integrity

Code

snippet
-- 部分排斥约束(partial exclusion constraint):
-- 只有满足 WHERE 的行参与冲突检测,已取消的预约不再挡道
CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TABLE bookings (
    id        integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    room      text      NOT NULL,
    cancelled boolean   NOT NULL DEFAULT false,
    stays     tstzrange NOT NULL,
    EXCLUDE USING gist (room WITH =, stays WITH &&) WHERE (NOT cancelled)
);

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

-- 与有效预约重叠:照常被拒
-- ERROR: conflicting key value violates exclusion constraint "bookings_room_stays_excl"
INSERT INTO bookings (room, stays)
VALUES ('skyline', '[2026-11-20 10:00, 2026-11-20 12:00)');

-- 取消后同一时段可以重订:被取消的行退出冲突检测
UPDATE bookings SET cancelled = true WHERE room = 'skyline';
INSERT INTO bookings (room, stays)
VALUES ('skyline', '[2026-11-20 09:30, 2026-11-20 10:30)');

-- 不同房间互不影响:room 的 = 参与判断
INSERT INTO bookings (room, stays)
VALUES ('atrium', '[2026-11-20 09:00, 2026-11-20 11:00)');

Partial exclusion

The EXCLUDE USING gist clause pairs room WITH = with stays WITH && so overlapping ranges in the same room conflict. The WHERE (NOT cancelled) suffix scopes the whole constraint: rows with cancelled = true leave the conflict detection entirely.

The four statements

The first overlapping insert is rejected with the conflicting key value violates exclusion constraint error; after UPDATE bookings SET cancelled = true, the same time window rebooks cleanly; a different room (atrium) never conflicts because the = arm keeps rooms separate.

Why btree_gist

GiST alone cannot index scalar equality on text; the btree_gist extension provides the = operator class for room, which is why the snippet runs CREATE EXTENSION IF NOT EXISTS btree_gist first.

Interactive Tools for This Topic

FAQ

What does the WHERE clause change about the exclusion constraint?
Only rows satisfying WHERE (NOT cancelled) participate in conflict detection, so cancelled bookings stop blocking the same window while active ones still fail.
Why is the btree_gist extension required here?
GiST has no scalar equality operator class for text; btree_gist supplies it so the room WITH = arm of the constraint can be indexed.