Get Started Free

How to upsert in PostgreSQL (INSERT ... ON CONFLICT)

Insert a row or update it if it already exists, with INSERT ... ON CONFLICT DO UPDATE or DO NOTHING, EXCLUDED, multi-row upserts and MERGE.

Updated November 26, 2026 ยท Tested on PostgreSQL 16.14

Quick Answer

Add ON CONFLICT to the insert, naming the unique column, and use EXCLUDED for the values you tried to insert:

INSERT INTO products (sku, name, stock)
VALUES ('A1', 'Mug', 5)
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name,
    stock = EXCLUDED.stock;

To skip rows that already exist instead of updating them, use ON CONFLICT (sku) DO NOTHING.

How ON CONFLICT works

A plain insert of a key that already exists fails:

ERROR:  duplicate key value violates unique constraint "products_pkey"
DETAIL:  Key (sku)=(A1) already exists.

ON CONFLICT tells PostgreSQL what to do instead. The check and the write are a single atomic statement, so two sessions upserting the same key at the same time can't both insert. That is the reason to use it over "SELECT, then INSERT or UPDATE" in application code, which races.

ClauseWhat happens on a duplicate
ON CONFLICT (sku) DO NOTHINGThe row is skipped. No error.
ON CONFLICT (sku) DO UPDATE SET ...The existing row is updated.
ON CONFLICT ON CONSTRAINT name ...Same, naming the constraint instead of the columns.

In VisuaLeaf

Write and check upserts in VisuaLeaf

VisuaLeaf's SQL editor has an upsert snippet in autocomplete, so you start from the right INSERT ... ON CONFLICT shape. Because a buffer with several statements gives one result tab each, you can run the upsert and the queries that check it together:

INSERT INTO products (sku, stock) VALUES ('A-1', 5)
ON CONFLICT (sku) DO UPDATE SET stock = EXCLUDED.stock
RETURNING id, (xmax = 0) AS inserted;

SELECT last_value FROM products_id_seq;

The second tab shows the sequence moving even when the row was updated, which is the gap behaviour measured above. Save the statement to the query library with Ctrl/Cmd+S. Saved queries can use bound parameters such as :sku, which VisuaLeaf asks for each time you run it.

VisuaLeaf SQL editor on a PostgreSQL connection with Save, History and Run buttons above a query
The SQL editor: run the whole buffer or just a selection.

See the SQL Editor docs.

EXCLUDED and the existing row

Inside DO UPDATE, EXCLUDED is the row you tried to insert, and the table name refers to the row already there. That lets you merge the two instead of overwriting:

-- add to the stock instead of replacing it
INSERT INTO products (sku, name, stock)
VALUES ('A1', 'Mug', 3)
ON CONFLICT (sku) DO UPDATE
SET stock = products.stock + EXCLUDED.stock,
    updated_at = now();

Add a WHERE to update only when something changed. Rows that don't match aren't rewritten at all (see the measurement below):

INSERT INTO products (sku, stock) VALUES ('A1', 9)
ON CONFLICT (sku) DO UPDATE
SET stock = EXCLUDED.stock
WHERE products.stock IS DISTINCT FROM EXCLUDED.stock;

Upsert many rows and tell inserts from updates

ON CONFLICT works with multi-row VALUES and with INSERT ... SELECT. RETURNING gives back the final rows, and the xmax = 0 trick tells you which were new:

INSERT INTO products (sku, name)
VALUES ('B2', 'Plate'), ('A1', 'Mug v3')
ON CONFLICT (sku) DO UPDATE SET name = EXCLUDED.name
RETURNING sku, name, (xmax = 0) AS inserted;
 sku |  name  | inserted
-----+--------+----------
 B2  | Plate  | t
 A1  | Mug v3 | f

The same key can't appear twice in one statement. PostgreSQL rejects it with ON CONFLICT DO UPDATE command cannot affect row a second time. De-duplicate the input first, for example with SELECT DISTINCT ON (sku) ....

xmax = 0 relies on an internal system column. It works on current versions, but treat it as a convenience, not a contract.

The conflict target needs a unique index

The columns in ON CONFLICT (...) must match a unique index or constraint exactly. Otherwise:

ERROR:  there is no unique or exclusion constraint matching the ON CONFLICT specification

Add the constraint, then retry:

ALTER TABLE products ADD CONSTRAINT products_sku_key UNIQUE (sku);

Expression indexes work too, as long as the conflict target repeats the expression. This is how you upsert on a case-insensitive email:

CREATE UNIQUE INDEX users_email_lower ON users (lower(email));

INSERT INTO users (email) VALUES ('a@example.com')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email;

MERGE (PostgreSQL 15+)

PostgreSQL 15 added the SQL-standard MERGE, which can also delete and can join against any source table:

MERGE INTO products t
USING (VALUES ('D4', 'Cup', 2)) AS s(sku, name, stock)
ON t.sku = s.sku
WHEN MATCHED THEN UPDATE SET stock = t.stock + s.stock
WHEN NOT MATCHED THEN INSERT (sku, name, stock) VALUES (s.sku, s.name, s.stock);

For a simple insert-or-update, prefer ON CONFLICT. Under concurrent inserts of the same key, MERGE can still fail with a unique violation, while ON CONFLICT is designed to handle that case. MERGE ... RETURNING only exists from PostgreSQL 17; on 16 it is a syntax error.

What we found testing upserts

We ran these on PostgreSQL 16.14 in Docker, on a table with a serial primary key and a unique sku column.

1. Every conflicting row burns a sequence value, even with DO NOTHING. After inserting 1,000 rows, the sequence was at 1,000. Upserting the same 1,000 SKUs again took it to 2,000, and a DO NOTHING pass took it to 3,000, even though that pass inserted 0 rows. The next new row got id 3,001.

2. MERGE doesn't burn ids for matched rows. A MERGE over the same 1,000 existing SKUs updated all of them and left the sequence unchanged, because MERGE only evaluates the INSERT branch for rows that don't match. If id gaps bother you on a mostly-update workload, that is a real difference.

3. A no-op DO UPDATE still rewrites every row. Upserting 100,000 unchanged rows took 1.11 s, left 100,000 dead tuples, and doubled the table from 5.0 MB to 10.0 MB (autovacuum off so we could see it). The same statement with WHERE products.price IS DISTINCT FROM EXCLUDED.price took 0.42 s, updated 0 rows and the table didn't grow.

100,000 unchanged rowsTimeRows rewrittenTable size after
DO UPDATE SET price = EXCLUDED.price1.11 s100,0005.0 MB โ†’ 10.0 MB
Same, plus WHERE ... IS DISTINCT FROM ...0.42 s0unchanged

4. NULL keys never conflict. With a plain UNIQUE column, upserting NULL twice inserted two rows. ON CONFLICT only fires when the unique index would reject the row, and NULLs are distinct by default. On PostgreSQL 15+, declare the constraint UNIQUE NULLS NOT DISTINCT if one NULL key should be the limit.

5. A partial unique index needs its WHERE in the conflict target. With CREATE UNIQUE INDEX ON users (email) WHERE deleted_at IS NULL, plain ON CONFLICT (email) fails with "there is no unique or exclusion constraint matching the ON CONFLICT specification". ON CONFLICT (email) WHERE deleted_at IS NULL DO NOTHING works.

Other gotchas

  • DO NOTHING returns nothing for skipped rows. In our test, RETURNING on a two-row DO NOTHING insert returned only the new row. To get the existing row's id, select it afterwards or use a DO UPDATE.
  • Triggers. On a conflict, BEFORE INSERT triggers have already fired, and the UPDATE triggers fire for the update.

Frequently Asked Questions

Does PostgreSQL have an UPSERT command?

Not by that name. INSERT ... ON CONFLICT DO UPDATE, added in PostgreSQL 9.5, is PostgreSQL's upsert. PostgreSQL 15 also added MERGE.

What is EXCLUDED in PostgreSQL?

A special table name available in ON CONFLICT DO UPDATE. It holds the row that was proposed for insertion, so EXCLUDED.stock is the value you tried to insert.

How do I insert a row only if it does not exist?

INSERT ... ON CONFLICT (key) DO NOTHING. It needs a unique index on the key; without one there is nothing to conflict with.

Why does my id sequence have gaps after upserts?

ON CONFLICT draws the next sequence value before it checks for a conflict, so every skipped or updated row uses up an id. In our test, 1,000 conflicting rows advanced the sequence by 1,000 even with DO NOTHING. MERGE does not do this for matched rows.

Is ON CONFLICT safe under concurrency?

Yes. It guarantees an insert or an update for each row even when many sessions upsert the same key at once, without unique-violation errors.

VisuaLeaf

Write and test upserts in VisuaLeaf

VisuaLeaf's SQL editor runs PostgreSQL queries with visual output, so you can check what an upsert returned, then open the table it changed and check its constraints in the table view.