Deferrable EXCLUDE Constraint Shifts Schedule Ranges

Declare a GiST EXCLUDE constraint DEFERRABLE INITIALLY IMMEDIATE so a transaction can defer checks and shift overlapping schedule slots safely.

SqlData Integrity

Code

snippet
CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TEMP TABLE room_shifts (
    shift_id integer PRIMARY KEY,
    room     text NOT NULL,
    slot     tsrange NOT NULL,
    CONSTRAINT excl_room_shift_overlap
        EXCLUDE USING gist (room WITH =, slot WITH &&)
        DEFERRABLE INITIALLY IMMEDIATE
);

INSERT INTO room_shifts VALUES
    (1, 'lab-a', '[2026-11-24 09:00, 2026-11-24 10:00)'),
    (2, 'lab-a', '[2026-11-24 10:00, 2026-11-24 11:00)');

BEGIN;
-- Defer overlap enforcement until COMMIT so shifts can move through a shared window
SET CONSTRAINTS excl_room_shift_overlap DEFERRED;

UPDATE room_shifts SET slot = '[2026-11-24 09:30, 2026-11-24 10:30)' WHERE shift_id = 1;
UPDATE room_shifts SET slot = '[2026-11-24 10:30, 2026-11-24 11:30)' WHERE shift_id = 2;

-- Force immediate check before COMMIT if you want to fail early
SET CONSTRAINTS excl_room_shift_overlap IMMEDIATE;
COMMIT;

SELECT shift_id, room, slot::text FROM room_shifts ORDER BY shift_id;

Stepwise trace — Deferrable EXCLUDE Constraint Shifts Schedule Ranges

The file runs SELECT / INSERT / UPDATE / CREATE statements, touching room_shifts.

room_shifts creates ephemeral scratch tables inline during execution without needing pre-existing tables and removes them cleanly as soon as this session closes.

Clause by clause, expect: a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Setup is internal: the session-local tables it queries (room_shifts) are made by the file, so a single complete run against a scratch database suffices.

Statements that matter

CREATE TEMP TABLE room_shifts (
    shift_id integer PRIMARY KEY,
    room     text NOT NULL,
    slot     tsrange NOT NULL,
    CONSTRAINT excl_room_shift_overlap
        EXCLUDE USING gist (room WITH =, slot WITH &&)
        DEFERRABLE INITIALLY IMMEDIATE
);
UPDATE room_shifts SET slot = '[2026-11-24 09:30, 2026-11-24 10:30)' WHERE shift_id = 1;
UPDATE room_shifts SET slot = '[2026-11-24 10:30, 2026-11-24 11:30)' WHERE shift_id = 2;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`room_shifts`.