Deferrable Unique Constraint Swap
Swap unique values between rows inside one transaction by declaring the UNIQUE constraint DEFERRABLE INITIALLY DEFERRED and checking at COMMIT.
Code
-- 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
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.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.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 tables or CTEs does it reference?
- `board_slots`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.