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.
| skutext | qtyint4 | seendate |
|---|---|---|
| TEA-01 | 10 | 2026-03-01 |
| TEA-02 | 5 | 2026-03-01 |
the table.
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.
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');DO NOTHING inserts the rows that don't conflict and quietly skips the ones that do. the tag counts only what went in:
INSERT INTO stock VALUES ('TEA-01', 3, '2026-03-02'), ('TEA-03', 7, '2026-03-02')
ON CONFLICT (sku) DO NOTHING;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:
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;| skutext | qtyint4 | seendate |
|---|---|---|
| TEA-01 | 13 | 2026-03-03 |
| TEA-02 | 5 | 2026-03-01 |
| TEA-03 | 7 | 2026-03-02 |
| TEA-04 | 12 | 2026-03-03 |
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.
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;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.
-- 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;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;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.
- 1INSERT INTO stock VALUES ('TEA-01', 3, '2026-03-05')
- 2ON CONFLICT (sku) DO NOTHING
- 3RETURNING sku, qty;
| skutext | qtyint4 |
|---|
(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.
the same refusal on shop, where products has a unique constraint on sku but not on name:
INSERT INTO products (sku, name, price) VALUES ('BOO-0300', 'the art of sql', 30.00)
ON CONFLICT (name) DO NOTHING;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:
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;| idint4 | skutext | pricenumeric |
|---|---|---|
| 3 | BOO-0003 | 30.00 |
| idint4 | skutext | pricenumeric |
|---|---|---|
| 202 | BOO-0300 | 38.00 |
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:
| sku | qty |
|---|---|
| TEA-01 | 10 |
T1 opens a transaction.
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:
INSERT INTO products (sku, name, price) VALUES ('BOO-0003', 'the art of sql', 30.00)
ON CONFLICT (sku) DO NOTHING
RETURNING id;| idint4 |
|---|
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.