Sub topic 7
MERGE or INSERT ... ON CONFLICT
PostgreSQL gives you two ways to say "update this row if it exists, otherwise insert it". INSERT ... ON CONFLICT has existed since PostgreSQL 9.5. MERGE arrived in PostgreSQL 15. They overlap on the simple upsert, but they are built on different mechanisms and behave differently under concurrency. This chapter helps you pick the right one.
What this chapter assumes
You should know the MERGE structure (target, USING source, ON condition), the WHEN MATCHED and WHEN NOT MATCHED clauses, and why each target row may be matched by at most one source row. You should also know what a unique constraint is and that PostgreSQL's default isolation level is READ COMMITTED. The examples reuse the inventory and inventory_updates tables from earlier in the tutorial.
Two mechanisms, one visible overlap
The two statements work in different ways:
MERGEis a join. PostgreSQL joins the source to the target on yourONcondition, then applies the firstWHENclause that fits each joined row. It does not need a unique index, because theONcondition can be any expression.INSERT ... ON CONFLICTis an insert that has a fallback. PostgreSQL tries to insert each row. If the insert would violate a unique index (the arbiter index), it runs theDO UPDATEorDO NOTHINGaction on the existing row instead.
That difference explains almost every point in the rest of this chapter.
The same upsert, both ways
Start with the data from the setup example: inventory holds bolt (100) and nut (50), and inventory_updates holds nut (+25) and washer (+40).
The MERGE version:
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);The ON CONFLICT version:
INSERT INTO inventory (product_id, name, quantity)
SELECT product_id, name, delta
FROM inventory_updates
ON CONFLICT (product_id) DO UPDATE
SET quantity = inventory.quantity + EXCLUDED.quantity,
updated_at = now();Both leave nut at 75 and add washer at 40. Three details differ:
MERGEnames the source assand the target ast.ON CONFLICThas no source alias. It refers to the proposed row through the specialEXCLUDEDtable and to the existing row through the target table name (or its alias).ON CONFLICT (product_id)is a conflict target. It must match a unique index or constraint, here the primary key.MERGEhas no such requirement.- The
ON CONFLICTform needs theINSERTcolumn list to be valid for new rows, which means supplyingnameandquantity. InMERGE, the insert only runs for unmatched rows, so the column list belongs only to that branch.
Where INSERT ... ON CONFLICT is the better choice
Concurrent writers hitting the same keys
ON CONFLICT DO UPDATE guarantees that, absent other errors, each row ends as either an insert or an update, even under heavy concurrency. PostgreSQL achieves this by inserting speculatively and checking the unique index. If another transaction has inserted the same key, it waits for that transaction and then updates the row.
MERGE does not offer this guarantee. It first looks for a matching target row. If none is visible and another session inserts the same key before you do, your INSERT branch can fail with a unique violation. The PostgreSQL documentation points to ON CONFLICT for this case.
Idempotent inserts
DO NOTHING is the shortest way to say "insert this unless it is already there":
INSERT INTO inventory (product_id, name, quantity)
VALUES (1, 'bolt', 5)
ON CONFLICT DO NOTHING;Without a conflict target, DO NOTHING skips a conflict on any unique index. The statement is safe to retry, which suits event ingestion and message deduplication.
Older servers
ON CONFLICT works on PostgreSQL 9.5 and later. If you must support versions before 15, MERGE is not available.
Costs to know about
ON CONFLICT has quirks of its own. BEFORE INSERT row triggers fire for every proposed row, including rows that then conflict. Columns that default from a sequence consume a sequence value for each proposed row, so conflicts leave gaps in serial or identity numbers.
Where MERGE is the better choice
Deleting as part of the sync
ON CONFLICT can only insert or update. It cannot delete. When a quantity reaches zero and the row should disappear, you need MERGE:
MERGE INTO inventory AS t
USING (
SELECT product_id, max(name) AS name, sum(delta) AS delta
FROM inventory_updates
GROUP BY product_id
) AS s
ON t.product_id = s.product_id
WHEN MATCHED AND t.quantity + s.delta <= 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED AND s.delta > 0 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);This one statement deletes, updates, or inserts per row, depending on conditions that can use both the target and the source columns.
Matching on something other than a unique key
MERGE joins on any condition. You can match on a non-unique column, a composite expression, or a range, as long as each target row is matched at most once. ON CONFLICT only reacts to a unique index violation, so it cannot express "match on lower(email)" unless a unique index on lower(email) exists.
Different actions for different rows
A single ON CONFLICT DO UPDATE can carry one WHERE filter, and it applies to every conflicting row. MERGE can have several WHEN MATCHED AND ... clauses, each with its own action. It can also skip a row by using DO NOTHING in a clause, or by having no clause match.
Full synchronization on PostgreSQL 17
With PostgreSQL 17 or later, MERGE can also act on target rows that have no source row:
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
RETURNING merge_action() AS action, t.product_id, t.quantity;merge_action() reports INSERT, UPDATE, or DELETE for each returned row. ON CONFLICT has RETURNING too, but it cannot tell you which branch ran without relying on tricks, and it has nothing like NOT MATCHED BY SOURCE.
Side-by-side comparison
| Question | MERGE | INSERT ... ON CONFLICT |
|---|---|---|
| First available in | PostgreSQL 15 | PostgreSQL 9.5 |
| Needs a unique index | No | Yes, for `DO UPDATE` |
| Possible actions | Insert, update, delete, do nothing | Insert, update, do nothing |
| Match condition | Any join condition | A unique index violation |
| Several conditional branches | Yes, many `WHEN` clauses | One `DO UPDATE ... WHERE` |
| Duplicate source rows for one key | Error: cardinality violation | Error: cannot affect row a second time (`DO UPDATE`) |
| Unique violation under concurrency | Possible | Prevented for the arbiter index |
| Rows missing from source | `NOT MATCHED BY SOURCE` (17+) | Not supported |
| `RETURNING` | PostgreSQL 17+, with `merge_action()` | Yes, since 9.5 |
Duplicates in the source behave similarly
Both statements refuse to touch the same target row twice in one command. If inventory_updates contained two rows for product 3, the ON CONFLICT DO UPDATE form would fail with "ON CONFLICT DO UPDATE command cannot affect row a second time". The MERGE form would fail with a cardinality violation if both source rows matched an existing target row.
The fix is identical: aggregate or deduplicate the source before the statement, as the GROUP BY product_id subquery did in the delete example. There is one small difference with MERGE. If both duplicate rows are unmatched, each takes the INSERT branch, and the second insert then fails on the primary key. Either way the source needs one row per key.
A decision flow
If you need both delete logic and safety against concurrent inserts, you can run MERGE inside a transaction and retry on a unique violation. You can also serialize the writers, for example with an advisory lock.
Common mistakes
- Writing
ON CONFLICT (col)when no unique index exists oncol. PostgreSQL reports "there is no unique or exclusion constraint matching the ON CONFLICT specification". The index must match the conflict target exactly, including any partial-index predicate. - Using
ON CONFLICTand expecting a delete. It cannot do one, so useMERGE. - Reading
EXCLUDEDas the old row.EXCLUDEDis the row you tried to insert. The existing row is the target table or its alias. - Expecting
MERGEto be retry-safe under parallel loads. It is not, as the warning above explains. - Skipping source aggregation, then hitting either duplicate-row error in production because the test data happened to be clean.
- Using
MERGE ... RETURNINGon a server older than 17. It is a syntax error there.
Exercises
Exercise
A nightly job loads a feed into a staging table, and the target has a unique key on sku. Some feed rows mean "discontinued" and must delete the matching target row. Which statement fits, and why?
Show answer
MERGE. INSERT ... ON CONFLICT cannot delete rows. A WHEN MATCHED AND s.discontinued THEN DELETE clause, followed by a plain WHEN MATCHED THEN UPDATE and a WHEN NOT MATCHED THEN INSERT, covers all three outcomes in one statement. Aggregate the feed to one row per sku first.
Exercise
Ten application servers each insert page-view counters keyed by (page_id, day), and the same key often arrives from several servers at once. The target has a unique index on (page_id, day). Which statement is safer, and what would you write?
Show answer
INSERT ... ON CONFLICT, because it guarantees an insert or an update without a unique violation for the arbiter index. For example: INSERT INTO page_views (page_id, day, views) VALUES ($1, $2, $3) ON CONFLICT (page_id, day) DO UPDATE SET views = page_views.views + EXCLUDED.views;. A MERGE could fail with SQLSTATE 23505 when two servers insert the same new key at the same moment.
Exercise
On PostgreSQL 16, you want a statement that inserts new rows, updates existing ones, and deletes target rows that are absent from the source. Is WHEN NOT MATCHED BY SOURCE an option, and what can you do instead?
Show answer
No. WHEN NOT MATCHED BY SOURCE needs PostgreSQL 17 or later. On 16 you can run a separate DELETE FROM target t WHERE NOT EXISTS (SELECT 1 FROM source s WHERE s.id = t.id) in the same transaction as the MERGE, or upgrade to 17 to do it in one statement.