skip to content

INSERT ... ON CONFLICT

insert or update in one statement. EXCLUDED, the arbiter index, and two sessions racing for the same key.

address
everything.writes.upsert
part
part 5, changing data
chapter
chapter 4 of 10
reading time
9 min

INSERT ... ON CONFLICT inserts a row, or does something else when a unique index says the key is taken: DO NOTHING skips it, DO UPDATE updates the row that's there. inside DO UPDATE, EXCLUDED is the row you tried to insert.

it's the only upsert that's safe when two sessions insert the same key at once: one waits, then updates. a SELECT followed by an INSERT isn't.

the picture

you know the "insert it, or if it's already there, update it" logic every app ends up writing? stock counts, page views, a settings row per user. it looks like two steps: look, then decide. that's exactly the problem, because between your look and your write, someone else can look too.

think of a guest list at a door. "is Ada on the list? no? write her down." two doormen asking at the same moment both get "no", and Ada ends up on the list twice (or, with a unique key, one of them gets an error). ON CONFLICT is one doorman with one pen: the check and the write happen as one step, at the index.

before anything runs
stock, after this step
stock after: before
skutextqtyint4seendate
TEA-01102026-03-01
TEA-0252026-03-01
(2 rows)
new rowchanged

the table.

step 1/6
real output, postgres 18.6 (PGlite 0.5.12) · upsert
step through six statements on a small stock table. a plain INSERT of an existing sku fails outright. DO NOTHING skips it. DO UPDATE changes the existing row (hot) and inserts the new one (live). a WHERE can turn the update down, and the same key twice in one statement is an error.

everything below runs on a fresh copy of the database each time, so nothing you do here sticks.

DO NOTHING and DO UPDATE

the shape is an ordinary INSERT with one more clause: what counts as a conflict (the conflict target, a column list in parentheses), and what to do about it.

stock.sqlempty db · session stock
CREATE TABLE stock (
  sku  text PRIMARY KEY,
  qty  int  NOT NULL,
  seen date NOT NULL
);
INSERT INTO stock VALUES ('TEA-01', 10, '2026-03-01'), ('TEA-02', 5, '2026-03-01');
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 2

DO NOTHING inserts the rows that don't conflict and quietly skips the ones that do. the tag counts only what went in:

sqlempty db · session stock
continues session stock (1 earlier block run first)
INSERT INTO stock VALUES ('TEA-01', 3, '2026-03-02'), ('TEA-03', 7, '2026-03-02')
ON CONFLICT (sku) DO NOTHING;
output, from postgres 18.6
INSERT 0 1

DO UPDATE runs an UPDATE on the existing row instead. in its SET and WHERE, the table's own name means the row that's already there, and EXCLUDED means the row you proposed, the one that was excluded from going in:

sqlempty db · session stock
continues session stock (2 earlier blocks run first)
INSERT INTO stock VALUES ('TEA-01', 3, '2026-03-03'), ('TEA-04', 12, '2026-03-03')
ON CONFLICT (sku) DO UPDATE
SET qty = stock.qty + EXCLUDED.qty, seen = EXCLUDED.seen;
 
SELECT * FROM stock ORDER BY sku;
output, from postgres 18.6
#1 · INSERT 0 2
#2 · SELECT 4
skutextqtyint4seendate
TEA-01132026-03-03
TEA-0252026-03-01
TEA-0372026-03-02
TEA-04122026-03-03
(4 rows)

INSERT 0 2: one row inserted, one updated, and the tag counts both. TEA-01 went from 10 to 13. (to tell which row took which path, ask RETURNING for old.sku IS NULL, new in postgres 18.)

a WHERE after DO UPDATE decides whether the update happens at all. the classic use: only accept newer data.

sqlempty db · session stock
continues session stock (3 earlier blocks run first)
INSERT INTO stock VALUES ('TEA-02', 99, '2026-02-01')
ON CONFLICT (sku) DO UPDATE
SET qty = EXCLUDED.qty, seen = EXCLUDED.seen
WHERE EXCLUDED.seen > stock.seen;
output, from postgres 18.6
INSERT 0 0

INSERT 0 0: the row conflicted, the WHERE said no, and the row was left alone. it still counts as handled: no error, no insert.

predict the output
sql
-- TEA-02 has qty 5
INSERT INTO stock VALUES ('TEA-02', 1, '2026-03-04'),
                         ('TEA-02', 2, '2026-03-04')
ON CONFLICT (sku) DO UPDATE
SET qty = stock.qty + EXCLUDED.qty;
sqlempty db · session stock
continues session stock (4 earlier blocks run first)
INSERT INTO stock VALUES ('TEA-02', 1, '2026-03-04'), ('TEA-02', 2, '2026-03-04')
ON CONFLICT (sku) DO UPDATE
SET qty = stock.qty + EXCLUDED.qty;
output, from postgres 18.6
ERROR 21000: ON CONFLICT DO UPDATE command cannot affect row a second time
HINT: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.

the arbiter index

ON CONFLICT (sku) doesn't mean "if sku is equal to something". it means "find the unique index on exactly (sku), and use it". that index is the arbiter: the thing that detects the conflict, and the thing that makes it safe under concurrency.

target =
action =
stock.sql
  1. 1INSERT INTO stock VALUES ('TEA-01', 3, '2026-03-05')
  2. 2ON CONFLICT (sku) DO NOTHING
  3. 3RETURNING sku, qty;
the result for (sku) | DO NOTHING
skutextqtyint4
(0 rows)

(sku) names the primary key's column, so the primary key's index is the arbiter. TEA-01 conflicts and is skipped: no rows back.

real output, postgres 18.6 (PGlite 0.5.12) · upsert
the same insert of TEA-01, which exists, with four conflict targets and both actions. a target names a unique index, by its columns or by its constraint's name. qty has no unique index, so there's nothing to arbitrate with. and DO UPDATE has to know which conflict it's for, so it needs a target; DO NOTHING doesn't.

the same refusal on shop, where products has a unique constraint on sku but not on name:

sqldb=shop
INSERT INTO products (sku, name, price) VALUES ('BOO-0300', 'the art of sql', 30.00)
ON CONFLICT (name) DO NOTHING;
output, from postgres 18.6
ERROR 42P10: there is no unique or exclusion constraint matching the ON CONFLICT specification

arbiters must be unique indexes or constraints that aren't deferrable. a partial unique index works too, if you repeat its WHERE in the conflict target.

and upserts burn sequence values. the INSERT computes the whole proposed row, defaults and identity included, before it finds out it has to update instead:

sqldb=shop
INSERT INTO products (sku, name, price) VALUES ('BOO-0003', 'the art of sql', 30.00)
ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price
RETURNING id, sku, price;
 
INSERT INTO products (sku, name, price) VALUES ('BOO-0300', 'sql antipatterns', 38.00)
RETURNING id, sku, price;
output, from postgres 18.6
#1 · INSERT 0 1
idint4skutextpricenumeric
3BOO-000330.00
(1 row)
#2 · INSERT 0 1
idint4skutextpricenumeric
202BOO-030038.00
(1 row)

the first upsert updated product 3, and still took 201 from the sequence. the new book gets 202. a table that's mostly upserted can burn through ids much faster than it grows. (INSERT has more on gaps; they're harmless.)

two sessions, one key

here's why ON CONFLICT exists, rather than every app writing the two steps itself. two sessions, both delivering TEA-02, which nobody has in stock yet:

upsert by =
T1
·
T2
·
1
BEGIN
committed in the database
skuqty
TEA-0110

T1 opens a transaction.

step 1/5
real output, a postgres 18.6 server · upsert-race
switch between the three runs, and step through. each is two real sessions on a postgres 18.6 server. in each, T2 waits on T1's transaction (the dashed lane). what T2 does when it wakes up is the whole difference. the table on the right is what's committed after each step.

with ON CONFLICT, T2 goes to the unique index first. it finds T1's entry for TEA-02, not committed yet, so it can't know whether it's a conflict. it waits on T1's transaction id. when T1 commits, T2 checks again, finds a committed row, and takes the DO UPDATE path. the manual promises exactly this: with DO UPDATE, every proposed row ends in an insert or an update, "even under high concurrency", unless some other error gets in the way.

with check-then-insert, both SELECTs run before either INSERT, so both see no row. both decide to insert. the unique index still saves the data (there's only one TEA-02), but it does it with an error: T2's transaction dies with 23505, and the 3 teas it was delivering are lost unless the application catches that and retries.

and if T1 rolls back instead (the second option), T2 wakes to find no conflict at all and inserts its own row. either way, no error. how the unique check waits on another transaction is in how a unique index says no, and the ShareLock on a transaction id that T2 waits for shows up in pg_locks.

one level deeperwhat DO NOTHING returns

RETURNING only returns rows the statement inserted or updated. a row DO NOTHING skipped returns nothing, which breaks the "get the id, inserting it if needed" pattern:

sqldb=shop
INSERT INTO products (sku, name, price) VALUES ('BOO-0003', 'the art of sql', 30.00)
ON CONFLICT (sku) DO NOTHING
RETURNING id;
output, from postgres 18.6
INSERT 0 0
idint4
(0 rows)

zero rows. two ways out: follow up with a SELECT for the rows that didn't come back, or use a DO UPDATE that changes nothing (DO UPDATE SET sku = EXCLUDED.sku) so every row comes back. the second always returns the row, and always writes a new version of it, which on a hot key means bloat and WAL for nothing (an UPDATE is an INSERT).

keylines

  • ON CONFLICT (key) needs a unique index on exactly that key: the arbiter.
  • DO NOTHING skips conflicting rows. DO UPDATE updates them, with EXCLUDED as the proposed row.
  • a WHERE on DO UPDATE can turn an update down, and the row is left alone.
  • the same key twice in one statement is an error: deduplicate the batch.
  • under concurrency one session waits and then updates. check-then-insert gets a 23505 instead.