SET CONSTRAINTS DEFERRED Defers Unique Checks
Defer a unique constraint with SET CONSTRAINTS, shift every seat number in one transaction, and validate before commit.
Code
-- 可延迟唯一约束: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
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.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.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.
FAQ
- Which objects does the SQL touch?
- The references are `seats`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.