skip to content

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:

T1
·
T2
·
1
BEGIN; INSERT INTO k VALUES (5)→ INSERT 0 1
pg_locks
  • T1RowExclusiveLockk
  • T1ExclusiveLockxid 759
  • T1ExclusiveLock4/4

T1 inserts 5 and doesn't commit yet. its index entry for 5 is in the leaf already.

step 1/6
real output, a postgres 18.6 server · unique-wait
two sessions inserting the same key, twice. step through: T2's insert waits (dashed) on T1's transaction id, the ShareLock in the lock manager. when T1 commits, T2 gets 23505. in round two T1 rolls back, and T2's insert goes through.

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).

predict the output
T1 inserted 5 and hasn't committed. T2, in another session, inserts 5. what does T2 get?
sql
-- 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
drawn by hand · the control flow of _bt_check_unique in nbtinsert.c
what a unique check does with each equal key it finds, from _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:

sqldb=shop
INSERT INTO customers (id, name, country, created_at)
VALUES (42, 'Ada again', 'GB', '2026-01-01');
output, from postgres 18.6
ERROR 23505: duplicate key value violates unique constraint "customers_pkey"
DETAIL: Key (id)=(42) already exists.

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:

sqlempty db · ext=pageinspect · session redo
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 3
#3 · BEGIN
#4 · DELETE 1
#5 · INSERT 0 1
#6 · COMMIT
#7 · SELECT 4
itemoffsetint2ctidtiddeadbooldatatext
1(0,1)f01 00 00 00 00 00 00 00
2(0,2)f02 00 00 00 00 00 00 00
3(0,4)f02 00 00 00 00 00 00 00
4(0,3)f03 00 00 00 00 00 00 00
(4 rows)

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.

123577root,a leafheap 0
dead index entry
real output, a postgres 18.6 server · unique-wait
k_pkey after the two rounds. key 5 has one entry: T2's failed row at (0,5) never got one. key 7 has two: T1's aborted row, marked dead by T2's check, and T2's.

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+:

sqlempty db
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 2
#3 · CREATE TABLE
#4 · INSERT 0 1
#5 · ERROR 23505
ERROR 23505: duplicate key value violates unique constraint "b_email_key"
DETAIL: Key (email)=(null) already exists.
#6 · SELECT 1
a_rowsint8b_rowsint8
21
(1 row)

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:

sqlempty db
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE TABLE
#3 · INSERT 0 3
#4 · INSERT 0 3
#5 · ERROR 23505
ERROR 23505: duplicate key value violates unique constraint "plain_pkey"
DETAIL: Key (id)=(2) already exists.
#6 · UPDATE 3
#7 · SELECT 1
plainint4[]laterint4[]
{1,2,3}{2,3,4}
(1 row)

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:

sqlempty db
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · BEGIN
#3 · INSERT 0 1
#4 · INSERT 0 1
#5 · SELECT 1
rows_so_farint8
2
(1 row)
#6 · ERROR 23505
ERROR 23505: duplicate key value violates unique constraint "seat_n_key"
DETAIL: Key (n)=(1) already exists.
#7 · SELECT 1
rows_afterint8
0
(1 row)

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.