Measured on PostgreSQL 18.4: an immediate unique check fails a one-statement shift, DEFERRABLE INITIALLY IMMEDIATE fixes it, and deferrable keys cannot serve ON CONFLICT.
Reordering a list should not be hard
Jenya's reading-list feature at Belgavi's Book Store stores each list's books with an explicit position, and a unique constraint keeps two books from sharing a slot:
CREATE TABLE shelf (
id int PRIMARY KEY,
list_id int NOT NULL,
position int NOT NULL,
title text NOT NULL,
CONSTRAINT shelf_list_position_key UNIQUE (list_id, position)
);Moving a book to the top means shifting the others down by one: UPDATE shelf SET position = position + 1 WHERE list_id = 1. On PostgreSQL that statement fails with a duplicate key error on a perfectly ordinary list, even though the final state has no duplicates. Swapping two books in two statements fails too. The first workaround most teams find is to move rows to temporary negative positions and back, which works, doubles the writes and leaves everyone unsure why the obvious version did not.
The obvious version fails because of when the constraint is checked. PostgreSQL offers three timings, and only one of them is the default.
Three timings
- NOT DEFERRABLE, the default. The PostgreSQL documentation for
CREATE TABLEnotes that when a unique or primary key constraint is not deferrable, PostgreSQL checks uniqueness immediately whenever a row is inserted or modified. The SQL standard says uniqueness should be enforced only at the end of the statement, and the documentation recommends declaring the constraint deferrable but initially immediate to get standard-compliant behaviour. - DEFERRABLE INITIALLY IMMEDIATE. The check runs at the end of each statement. Intermediate states inside one statement are allowed, and a transaction can switch the constraint to deferred with
SET CONSTRAINTS. - DEFERRABLE INITIALLY DEFERRED. The check runs at commit. Intermediate states across several statements are allowed.
With a non-deferrable constraint, the shift fails or succeeds depending on the order in which the statement visits rows. Moving the row at position 1 to position 2 collides with the row still at position 2. The same statement under a deferrable constraint sees only the final state.
The worked example
The companion probe runs the same statements under all three modes on PostgreSQL 18.4. Each scenario starts from a fresh table holding positions 1 to 5 of one list, runs in a single transaction, and records success or the SQLSTATE.
| Scenario | NOT DEFERRABLE | DEFERRABLE INITIALLY IMMEDIATE | DEFERRABLE INITIALLY DEFERRED |
|---|---|---|---|
| Shift every position by one in one statement | 23505 | commits | commits |
| Swap two positions in one statement with CASE | 23505 | commits | commits |
| Swap two positions in two statements | 23505 | 23505 | commits |
| Same, after SET CONSTRAINTS ... DEFERRED | 42809, not deferrable | commits | commits |
| Leave a duplicate at commit | 23505 at the UPDATE | 23505 at the UPDATE | 23505 at COMMIT |
| Two-step negative offset | commits | commits | commits |
| INSERT ... ON CONFLICT on the constraint columns | commits | 55000 | 55000 |
| Foreign key referencing the constraint columns | commits | 55000 | 55000 |
The middle column is the one most teams want and few use. DEFERRABLE INITIALLY IMMEDIATE behaves exactly like the default for single-row changes and for duplicates that survive a statement, but lets one statement reorder a list. It also allows a transaction that genuinely needs several statements to opt into deferral with SET CONSTRAINTS shelf_list_position_key DEFERRED, without making every transaction pay for it.
The deferred row on duplicates is worth noticing. With INITIALLY DEFERRED, a statement that creates a duplicate succeeds, and the error appears at COMMIT, after the application may have done other work in the transaction believing the update was fine. Error handling written around the UPDATE will not see it.
Why the default case is order dependent
The probe also closes a gap: delete the row at position 1 and run UPDATE shelf SET position = position - 1. Under the non-deferrable constraint this committed with the default plan, a bitmap scan on the unique index, which visited the rows in their physical order, 2, 3, 4, 5. Each row moved into a slot that was already free.
After two earlier updates had moved rows to the end of the table, and with index and bitmap scans disabled for the transaction, the same statement visited the rows as 4, 5, 2, 3 and failed: position 4 tried to become 3 while the row at 3 had not moved yet. The SQL is identical. The outcome depends on the plan and on where rows physically sit, both of which change without anyone touching the code. A reorder that works on a freshly loaded table can start failing in production after vacuum and updates have rearranged the pages. Under either deferrable mode both versions committed.
What deferrability costs
Deferrable unique constraints are not free, and the probe shows the two limits that matter most.
ON CONFLICT cannot use them. INSERT ... ON CONFLICT (list_id, position) DO NOTHING failed with 55000, ON CONFLICT does not support deferrable unique constraints/exclusion constraints as arbiters. If any code path upserts on these columns, making the constraint deferrable breaks it. A workaround is a second, non-deferrable unique index on the same columns for the arbiter, but then that index enforces immediate checks and you are back where you started.
Foreign keys cannot reference them. Creating a table with a foreign key to (list_id, position) failed with 55000, cannot use a deferrable unique constraint for referenced table. Referencing positions is unusual, but referencing a natural key protected by a deferrable constraint is not.
There is also a runtime cost. For deferrable unique constraints PostgreSQL records potential conflicts as rows are written and rechecks them when the constraint fires, so a statement that touches many rows does more work than under an immediate check. For lists of tens or hundreds of items it is not measurable in practice; for bulk reorders of millions of rows, measure before switching.
Choosing an approach
- If nothing upserts on the columns and nothing references them, declare the constraint
DEFERRABLE INITIALLY IMMEDIATEand write reorders as single statements. This is the smallest change with the clearest semantics. - If you need multi-statement reorders, use
SET CONSTRAINTS ... DEFERREDinside those transactions only, and check for errors atCOMMIT. - If the constraint must stay non-deferrable, use the two-step negative offset: move the affected rows to
-position, then to their new positions. It works under every mode and costs one extra update per row. - Consider whether positions need to be dense integers at all. Fractional or gapped keys, such as positions spaced by 1,000, make most moves a single-row update and avoid the problem.
An existing unique constraint cannot be switched in place. On PostgreSQL 18.4, ALTER TABLE shelf ALTER CONSTRAINT shelf_list_position_key DEFERRABLE INITIALLY IMMEDIATE failed with 42809, constraint is not a foreign key constraint; the ALTER TABLE documentation confirms that only foreign keys can have their deferrability altered this way. Build a new unique index concurrently, add a deferrable constraint using it in the same transaction as dropping the old one, and schedule it like any index change.
Failure modes
- Error moves to COMMIT. Deferred checks surface at commit. ORMs and connection wrappers that do not inspect commit errors will report success for a failed transaction.
- Hidden upserts. A migration to deferrable breaks every
ON CONFLICTon those columns at run time, not at migration time. Search for them first. - Tests on fresh tables. The order-dependent failure of the default mode rarely shows on freshly inserted test data. Test reorders after updates, or simply do not rely on visit order.
- Swap via CASE across lists. A
CASEswap that forgets thelist_idpredicate can move rows between lists. The constraint will not catch it.
Verification
Run the probe with PG_DSN pointing at a scratch database; it drops and recreates its own tables and writes a JSON record of every statement. The companion tests check the recorded PostgreSQL 18.4 matrix offline and rerun the probe live when PG_DSN is set. In your own schema, the decisive check is to run your reorder statements under the constraint mode you choose, after the table has seen updates, and to confirm that your application observes errors raised at commit.