Sub topic 11
INSERT ON CONFLICT versus MERGE
This chapter assumes you have read the earlier chapters on ON CONFLICT DO NOTHING, DO UPDATE, and EXCLUDED. You should also be comfortable with unique constraints and with running statements in psql. By the end you should be able to translate an upsert between the two syntaxes, name the behaviors that differ, and pick one for a given job.
Two tools that overlap
PostgreSQL has two statements that can "insert the row, or change the existing one":
INSERT ... ON CONFLICTis a PostgreSQL extension. It is built around a unique index. You attempt an insert, and the conflict clause says what to do if that insert would violate uniqueness.MERGEis part of the SQL standard. PostgreSQL added it in version 15. It joins a source of rows to a target table and runs a different action for each combination of matched and unmatched rows.
The overlap is real, but the two statements answer different questions. ON CONFLICT asks, "Does this key already exist?" MERGE asks, "How does each source row relate to the target table, and what should I do about it?"
The same upsert in both forms
Both examples use the product_stock table from earlier chapters. The setup is repeated so you can run the chapter on its own.
CREATE TABLE IF NOT EXISTS product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- ON CONFLICT form
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();
-- MERGE form (PostgreSQL 15+)
MERGE INTO product_stock AS t
USING (VALUES ('A-100', 5)) AS s(sku, quantity)
ON t.sku = s.sku
WHEN MATCHED THEN
UPDATE SET quantity = s.quantity, updated_at = now()
WHEN NOT MATCHED THEN
INSERT (sku, quantity) VALUES (s.sku, s.quantity);The mapping between the two is mechanical:
| ON CONFLICT piece | MERGE piece |
|---|---|
| `VALUES (...)` or `SELECT` feeding the insert | `USING` source, given an alias |
| `ON CONFLICT (sku)` | `ON t.sku = s.sku` join condition |
| `EXCLUDED.quantity` | `s.quantity`, the source alias |
| `DO UPDATE SET ...` | `WHEN MATCHED THEN UPDATE SET ...` |
| `DO NOTHING` | omit the `WHEN MATCHED` branch, or write `WHEN MATCHED THEN DO NOTHING` |
| The insert itself | `WHEN NOT MATCHED THEN INSERT ...` |
In MERGE, the source columns have a name you choose, so there is no special EXCLUDED row. The target is whatever alias you gave after MERGE INTO.
What MERGE can do that ON CONFLICT cannot
Delete rows
ON CONFLICT can insert or update. It cannot delete. MERGE has a DELETE action, and each WHEN branch can carry its own extra condition. That lets one statement synchronize a table with a feed:
CREATE TEMP TABLE stock_feed (sku text, quantity integer);
INSERT INTO stock_feed VALUES ('A-100', 9), ('C-300', 4), ('D-400', 0);
MERGE INTO product_stock AS t
USING stock_feed AS s
ON t.sku = s.sku
WHEN MATCHED AND s.quantity = 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE SET quantity = s.quantity, updated_at = now()
WHEN NOT MATCHED AND s.quantity > 0 THEN
INSERT (sku, quantity) VALUES (s.sku, s.quantity);Walking through the feed:
A-100exists and has a nonzero quantity, so it is updated.C-300is new and nonzero, so it is inserted.D-400is new but has quantity 0. TheAND s.quantity > 0condition on the insert branch skips it.- If
D-400already existed, the first branch would delete it.
Branches are tested in the order written, and the first one whose condition holds is used. Put the more specific condition first, as above. If you swapped the two WHEN MATCHED branches, the plain update would catch every matched row and the delete would never run.
Join on something other than a unique key
ON CONFLICT needs a unique index or constraint to detect conflicts. MERGE has no such requirement, because it uses an ordinary join condition. You can match on several columns, on an expression, or on a range comparison, and no index is needed for the statement to be valid. An index on the join columns still helps performance, as with any join.
This flexibility has a cost. Without a unique constraint, nothing stops two concurrent MERGE statements from each inserting the same logical key, and you end up with duplicates. The unique index is what makes ON CONFLICT safe. MERGE gives that up for expressiveness.
Return what happened (PostgreSQL 17)
PostgreSQL 15 and 16 do not allow RETURNING on MERGE. PostgreSQL 17 added it, along with the merge_action() function, which reports INSERT, UPDATE, or DELETE for each row:
MERGE INTO product_stock AS t
USING (VALUES ('A-100', 5), ('E-500', 2)) AS s(sku, quantity)
ON t.sku = s.sku
WHEN MATCHED THEN
UPDATE SET quantity = s.quantity, updated_at = now()
WHEN NOT MATCHED THEN
INSERT (sku, quantity) VALUES (s.sku, s.quantity)
RETURNING merge_action() AS action, t.sku, t.quantity;With ON CONFLICT, RETURNING gives you the row but does not say whether it was inserted or updated. A common workaround is to also return xmax = 0. That trick depends on internal row-version details, so treat it as a diagnostic and not a stable interface. If you need the action reliably and you run PostgreSQL 17 or later, MERGE is the clearer tool.
PostgreSQL 17 also added a WHEN NOT MATCHED BY SOURCE branch. It handles target rows that have no counterpart in the source, for example to delete everything a feed no longer lists.
What ON CONFLICT does that MERGE does not
Behavior under concurrent writers
This is the main difference. An upsert has to be safe when two sessions race for the same key.
INSERT ... ON CONFLICT DO UPDATE guarantees that, for each proposed row, one of two things happens. Either the row is inserted, or an existing row is updated. It achieves this by inserting into the unique index first and, on a conflict, locking the existing row and updating it. Waiting on a concurrent transaction and retrying happens inside the statement. Unless something else goes wrong, you do not get a unique-violation error from the key you named.
MERGE works differently. It first runs the join to decide which rows are matched. Only then does it run the actions. If another transaction inserts the same key after the join but before your INSERT action runs, your insert hits the unique index and fails. Under the default READ COMMITTED isolation level, the statement raises the error:
ERROR: duplicate key value violates unique constraint "product_stock_pkey"The sequence looks like this:
With ON CONFLICT, Session A's insert would find the conflict, lock Session B's committed row, and update it.
MERGE does handle concurrent updates and deletes of rows it has already matched. In READ COMMITTED it re-checks the join and the WHEN conditions against the newer version of the row. The gap is in concurrent inserts of keys that did not exist when the statement began. If you use MERGE where concurrent inserts of the same key are possible, catch SQLSTATE 23505 (unique violation) and retry the statement.
Batch behavior with duplicate keys
Both statements reject a batch that tries to change the same target row twice. For MERGE, this happens when two source rows match the same target row:
ERROR: MERGE command cannot affect row a second timeON CONFLICT DO UPDATE gives the analogous "cannot affect row a second time" error for duplicate keys in one statement. The fix is the same for both: collapse duplicates in the source before the statement runs, for example with GROUP BY or DISTINCT ON. ON CONFLICT DO NOTHING is more forgiving. It silently skips later duplicates, which is sometimes convenient and sometimes hides a data problem.
Other differences
- Naming the arbiter.
ON CONFLICTlets you pick the constraint by column list, byON CONSTRAINT name, or by a partial index predicate.MERGEhas no concept of a conflict target. - Brevity. For the common case of one table and one key,
ON CONFLICTis shorter and harder to get subtly wrong. - Portability.
MERGEfollows the SQL standard and is close to what other databases offer, though each database differs in details such as concurrency semantics.ON CONFLICTruns only on PostgreSQL (and SQLite has a similar form). - Availability.
ON CONFLICThas existed since PostgreSQL 9.5.MERGEneeds 15 or later, and several features above need 17.
Side-by-side summary
| Question | INSERT ON CONFLICT | MERGE |
|---|---|---|
| Minimum version | 9.5 | 15 (17 for `RETURNING` and `NOT MATCHED BY SOURCE`) |
| Needs a unique index | Yes | No |
| Can delete rows | No | Yes |
| Different actions by condition | One `DO UPDATE ... WHERE` | Many `WHEN` branches with conditions |
| Concurrent insert of same key | Handled, no unique error | Can raise a unique violation |
| Reports insert vs. update | Not directly | `merge_action()` in 17+ |
| Duplicate keys in the batch | Error for `DO UPDATE`, skipped for `DO NOTHING` | Error if two source rows hit one target row |
Choosing between them
A practical rule:
- Use
INSERT ... ON CONFLICTfor application-level upserts: "save this record, whatever state the database is in". This is the case where concurrency safety matters most. - Use
MERGEfor set-based synchronization jobs, such as loading a staging table into a target, where you need deletes or several branches. Such jobs usually run from one writer or inside a controlled window, so the concurrent-insert gap rarely bites. - If you need both, such as a sync that must tolerate concurrent inserts, run
MERGEinside retry logic. Alternatively, split the work into anINSERT ... ON CONFLICTfor the upsert and a separateDELETEfor removals.
Common errors when switching
- Using
EXCLUDEDin a MERGE.EXCLUDEDexists only inON CONFLICT. InMERGE, refer to the source alias. - Forgetting that
MERGEhas no conflict detection. If the target has no unique index on the join columns, aMERGEcan insert duplicates without any error. - Expecting
RETURNINGon PostgreSQL 15 or 16. It is a syntax error there. Check the server version withSELECT version();. - Ordering
WHENbranches wrongly. A broadWHEN MATCHEDplaced before a narrower one makes the narrower branch unreachable. - Treating a retry-free
MERGEas safe in production. The race shown in the first diagram is rare in testing and appears under load.
Exercise
A nightly job loads a staging table into product_stock. Rows with quantity 0 must delete the product, other existing rows must be updated, and new nonzero rows must be inserted. Only this job writes to the table. Which statement fits best, and why?
Show answer
Use MERGE. It supports a DELETE action and conditional WHEN branches, so one statement covers all three cases, which ON CONFLICT cannot do alone because it has no delete. Because only one job writes to the table, the concurrent-insert gap in MERGE does not matter here. Put the WHEN MATCHED AND s.quantity = 0 THEN DELETE branch before the general WHEN MATCHED update, and add AND s.quantity > 0 to the insert branch so zero-quantity new rows are skipped.
Exercise
Two web requests try to create the same new sku at the same moment. One uses INSERT ... ON CONFLICT (sku) DO UPDATE, the other uses MERGE on sku. In READ COMMITTED, which statement can fail with SQLSTATE 23505, and what should the application do?
Show answer
The MERGE can fail. It decides between the matched and not-matched branches from its initial join, so if the other transaction commits the same key before MERGE runs its insert, the insert hits the primary key and raises a unique violation. The application should catch SQLSTATE 23505 and retry the MERGE, which will then see the row and take the WHEN MATCHED branch. The ON CONFLICT statement handles the conflict internally by updating the existing row, so it does not raise that error for the key it names.