how a unique index says no
checking for a live duplicate, waiting on a transaction that hasn't decided yet, and the 23505 at the end.
- address
- everything.index_internals.unique_checks
- part
- part 13, inside indexes
- chapter
- chapter 6 of 12
- reading time
- 8 min
a unique index checks for a duplicate before it adds the new entry: it finds every entry with the same key and asks the heap about each one's row. a committed, live row means 23505. a dead or aborted one doesn't count. a row from a transaction that hasn't finished yet can't be judged, so the insert waits for that transaction, then checks again.
the picture
you know how a unique constraint is enforced by a b-tree index? the index can find "is 5 already here?" in a few page reads. the hard part is what "already here" means in MVCC: an index entry has no idea whether its row is committed, deleted, rolled back, or still being written. the entry is just a key and an address.
think of booking a seat with a pencil. someone has written their name on seat 5 in pencil, and they're still on the phone deciding. you can't take the seat, and you can't tell them it's free either. so you wait by the desk. if they ink it in, you're out of luck (23505). if they rub it out, it's yours.
here's that, twice, on a real server:
- T1RowExclusiveLockk
- T1ExclusiveLockxid 759
- T1ExclusiveLock4/4
T1 inserts 5 and doesn't commit yet. its index entry for 5 is in the leaf already.
the wait is the important part. T2 doesn't wait on a page, a row lock, or the index: it waits on T1's transaction id. every transaction holds an exclusive lock on its own id until it ends, so "wait for this transaction to finish" is just a ShareLock request on that id (watching locks with pg_locks). that's the one index wait that does show up in pg_locks; page latches never do (b-trees under concurrency).
-- T1: BEGIN; INSERT INTO k VALUES (5); -- not committed
-- T2:
INSERT INTO k VALUES (5);what the check does
for the key being inserted, postgres walks every entry with an equal key (they sit side by side in the leaf, sometimes spilling to the next page), and for each one fetches the heap version it points to:
- ├── fetch its heap version
- ├── version is live and committed23505, duplicate key #dead
- ├──
- │ └── wait for that transaction to end, then redo the whole check
- └──
- └── skip itand if it's dead to everyone, mark the entry LP_DEAD
- no conflict foundinsert the new entry
_bt_check_unique in the postgres source. only a committed live row is a conflict; anything uncommitted means wait and start over.the ordinary case, a committed duplicate, needs no second session:
INSERT INTO customers (id, name, country, created_at)
VALUES (42, 'Ada again', 'GB', '2026-01-01');the DETAIL names the key. and the heap row was already written by then: postgres inserts the row first and the index entries after, so a failed insert leaves a dead heap tuple behind for VACUUM, like a rolled-back one.
dead and in-progress entries
"same key" doesn't mean "duplicate". a deleted row's entry stays in the index until VACUUM, and the check has to step over it. in one transaction, delete 2 and insert it again:
CREATE TABLE k (id int PRIMARY KEY);
INSERT INTO k VALUES (1), (2), (3);
BEGIN;
DELETE FROM k WHERE id = 2;
INSERT INTO k VALUES (2);
COMMIT;
SELECT itemoffset, ctid, dead, data
FROM bt_page_items('k_pkey', 1)
ORDER BY itemoffset;| itemoffsetint2 | ctidtid | deadbool | datatext |
|---|---|---|---|
| 1 | (0,1) | f | 01 00 00 00 00 00 00 00 |
| 2 | (0,2) | f | 02 00 00 00 00 00 00 00 |
| 3 | (0,4) | f | 02 00 00 00 00 00 00 00 |
| 4 | (0,3) | f | 03 00 00 00 00 00 00 00 |
two entries for 2 now: (0,2), the deleted version, and (0,4), the new one. the check found (0,2), saw it deleted by its own transaction, and let the insert through. an UPDATE that changes a key does the same thing in one statement.
and here's the end of round two of the race, read off the real leaf: two entries for 7. the first points at T1's rolled-back row. T2's unique check found it, waited, saw it aborted, and on the way past it marked the entry dead (the LP_DEAD hint, struck through), so the next scan or split can remove it without visiting the heap.
that marking is why a unique index cleans itself as it goes, and why the primary key in the churn experiment stayed smaller than the other indexes.
NULLs
the standard says a NULL isn't equal to anything, so a unique column can hold any number of them. postgres 15 added the other choice pg 15+:
CREATE TABLE a (email text UNIQUE);
INSERT INTO a VALUES (NULL), (NULL);
CREATE TABLE b (email text UNIQUE NULLS NOT DISTINCT);
INSERT INTO b VALUES (NULL);
INSERT INTO b VALUES (NULL);
SELECT (SELECT count(*) FROM a) AS a_rows, (SELECT count(*) FROM b) AS b_rows;| a_rowsint8 | b_rowsint8 |
|---|---|
| 2 | 1 |
the plain UNIQUE took two NULLs. NULLS NOT DISTINCT treats NULL as one value, and the second NULL got 23505, with (email)=(null) in the DETAIL. (a partial index is the other way to say "at most one row may have no email".)
checked when?
a plain unique constraint checks each row as it's written. that has a surprising consequence for updates that shift keys:
CREATE TABLE plain (id int PRIMARY KEY);
CREATE TABLE later (id int PRIMARY KEY DEFERRABLE);
INSERT INTO plain SELECT generate_series(1, 3);
INSERT INTO later SELECT generate_series(1, 3);
UPDATE plain SET id = id + 1;
UPDATE later SET id = id + 1;
SELECT (SELECT array_agg(id ORDER BY id) FROM plain) AS plain,
(SELECT array_agg(id ORDER BY id) FROM later) AS later;| plainint4[] | laterint4[] |
|---|---|
| {1,2,3} | {2,3,4} |
id = id + 1 on plain failed: postgres updated id 1 to 2 while the old 2 still existed, and 23505. the same statement on later worked: a DEFERRABLE constraint (even INITIALLY IMMEDIATE, the default) is checked at the end of the statement instead, when the keys are 2, 3, 4 and all different. the standard says unique constraints are checked at the end of each statement; postgres's non-deferrable ones check row by row, which is faster, and DEFERRABLE gets you the standard behaviour.
INITIALLY DEFERRED moves the check to COMMIT:
CREATE TABLE seat (n int UNIQUE DEFERRABLE INITIALLY DEFERRED);
BEGIN;
INSERT INTO seat VALUES (1);
INSERT INTO seat VALUES (1);
SELECT count(*) AS rows_so_far FROM seat;
COMMIT;
SELECT count(*) AS rows_after FROM seat;| rows_so_farint8 |
|---|
| 2 |
| rows_afterint8 |
|---|
| 0 |
two 1s sat in the table, visible to the transaction, until COMMIT, which then failed and rolled everything back: zero rows. the index still did the work: it holds both entries, notes that a recheck is due, and the recheck runs at commit. (NOT NULL, CHECK and UNIQUE and foreign keys have the design side.)
keylines
- a unique insert first looks at every entry with the same key, and asks the heap about each row.
- committed and live: 23505. dead or aborted: skipped, and marked dead in the index.
- inserted or deleted by a running transaction: wait on its transaction id, then check again.
- the waiting is in pg_locks as a ShareLock on a transactionid, not a page lock.
- NULLS NOT DISTINCT (15+) makes NULL count as a value. DEFERRABLE moves the check to the end of the statement, or to COMMIT.