SET CONSTRAINTS DEFERRED Defers Unique Checks

Defer a unique constraint with SET CONSTRAINTS, shift every seat number in one transaction, and validate before commit.

SqlData Integrity

Code

snippet
-- 可延迟唯一约束:SET CONSTRAINTS DEFERRED defers unique checks to commit
CREATE TABLE seats (
  row_label text NOT NULL,
  seat_no integer NOT NULL,
  CONSTRAINT seats_unique UNIQUE (row_label, seat_no)
    DEFERRABLE INITIALLY IMMEDIATE
);

INSERT INTO seats (row_label, seat_no)
VALUES ('A', 1), ('A', 2), ('A', 3);

BEGIN;
SET CONSTRAINTS seats_unique DEFERRED;

-- 1→2、2→3、3→4:中间状态会重复,但延迟到提交时检查
UPDATE seats SET seat_no = seat_no + 1 WHERE row_label = 'A';

-- 事务内提前检查;此时已无重复,可以通过
SET CONSTRAINTS seats_unique IMMEDIATE;

COMMIT;

SELECT row_label, seat_no FROM seats ORDER BY seat_no;

-- 对照:不延迟时,第一条 UPDATE 就会因重复键失败
-- UPDATE seats SET seat_no = seat_no + 1 WHERE row_label = 'A';

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with seats among the objects involved.

Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; UNIQUE constraints that keep duplicate values out.

Applying it

Run it in the seats database context.

Statements that matter

UPDATE seats SET seat_no = seat_no + 1 WHERE row_label = 'A';
CREATE TABLE seats (
row_label text NOT NULL,
seat_no integer NOT NULL,
CONSTRAINT seats_unique UNIQUE (row_label, seat_no)
DEFERRABLE INITIALLY IMMEDIATE
);
INSERT INTO seats (row_label, seat_no)
VALUES ('A', 1), ('A', 2), ('A', 3);

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `seats`.