Deferrable Unique Constraint Swap

Swap unique values between rows inside one transaction by declaring the UNIQUE constraint DEFERRABLE INITIALLY DEFERRED and checking at COMMIT.

SqlData Integrity

Code

snippet
-- DEFERRABLE INITIALLY DEFERRED:唯一性检查推迟到 COMMIT,行间交换唯一值才可能
CREATE TABLE board_slots (
  slot  integer NOT NULL,
  piece text    NOT NULL,
  CONSTRAINT uq_board_slot UNIQUE (slot) DEFERRABLE INITIALLY DEFERRED
);

INSERT INTO board_slots VALUES (1, 'rook'), (2, 'knight');

BEGIN;
-- 立即检查的约束会在第一条 UPDATE 处失败(slot=2 已被占用)
UPDATE board_slots SET slot = 2 WHERE piece = 'rook';
UPDATE board_slots SET slot = 1 WHERE piece = 'knight';
-- 想提前暴露违规:SET CONSTRAINTS ALL IMMEDIATE;(提交前强制检查一次)
COMMIT;

What the code does

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

What the statements actually assemble: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; UNIQUE constraints that keep duplicate values out.

Applying it

Run it in the board_slots database context.

Statements that matter

UPDATE board_slots SET slot = 1 WHERE piece = 'knight';
UPDATE board_slots SET slot = 2 WHERE piece = 'rook';
CREATE TABLE board_slots (
slot  integer NOT NULL,
piece text    NOT NULL,
CONSTRAINT uq_board_slot UNIQUE (slot) DEFERRABLE INITIALLY DEFERRED
);

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`board_slots`.