Video in progress
When do you need to make a unique constraint `DEFERRABLE INITIALLY DEFERRED`?
By default a unique check happens immediately after every row, so an UPDATE that swaps values fails in the intermediate state. A deferred constraint postpones the check to commit: if the state is correct at the end of the transaction, everything passes.
📖 Answer
The classic example is the order of items in a list, with (list_id, position) unique:
-- swap positions 1 and 2
UPDATE items SET position = CASE position WHEN 1 THEN 2 WHEN 2 THEN 1 END
WHERE list_id = 5 AND position IN (1, 2);
-- ERROR: duplicate key value violates unique constraint
PostgreSQL updates rows one by one, and after the first row there are two rows with position = 2.
The fix:
ALTER TABLE items
ADD CONSTRAINT items_list_pos_uq
UNIQUE (list_id, position) DEFERRABLE INITIALLY DEFERRED;
Now the check happens at commit. Or you make it DEFERRABLE INITIALLY IMMEDIATE and write SET CONSTRAINTS items_list_pos_uq DEFERRED only in the transaction that needs it. I like this variant, because everywhere else the error shows up immediately.
The cost:
- a deferred unique index can't be used as the arbiter for
ON CONFLICT; - it can't be the target of an FK (an FK requires a non-deferrable unique);
- the error comes at commit, so in Java the exception arrives not at
save()but when the transaction closes, and it's harder to tell from the log which row is to blame.
The same approach works for FKs too: a deferred FK is useful when you insert two mutually referencing rows in one transaction.
Sign up to mark studied questions and save your progress.