Sub topic 7
MERGE or INSERT ... ON CONFLICT
Assume you know basic SELECT, INSERT, UPDATE, and DELETE, joins, primary keys, unique constraints, aliases, subqueries, and basic transactions. PostgreSQL added MERGE in version 15. PostgreSQL has supported INSERT ... ON CONFLICT since version 9.5.
Both statements can implement an upsert. An upsert inserts a row when its key is new and updates an existing row when the key already exists. They solve different problems, however.
The main difference
INSERT ... ON CONFLICT starts with an insert. It handles a conflict with a unique or exclusion constraint by doing nothing or running an update.
MERGE starts with a comparison. It joins a source row to a target row, then chooses an action based on whether the rows matched. Its actions can include INSERT, UPDATE, DELETE, or no action.
| Requirement | Prefer `MERGE` | Prefer `INSERT ... ON CONFLICT` |
|---|---|---|
| Insert new rows and update existing rows | Works | Usually simpler |
| Delete matched rows conditionally | Works | Not directly |
| Choose among several actions | Works | Limited to conflict update or no action |
| Use a general join to match rows | Works | Conflict target must use a constraint or index |
| Perform a small atomic upsert | Usually more code | Usually the clearest choice |
| Use PostgreSQL 15 or earlier | Not available | Available |
The same upsert in both forms
Suppose inventory_updates contains changes to apply to inventory. The MERGE form expresses the match explicitly:
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 condition compares source rows with target rows. A matched source row updates the target. An unmatched source row inserts a new target row.
The equivalent INSERT ... ON CONFLICT statement treats product_id as the conflict target:
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();EXCLUDED represents the row that PostgreSQL attempted to insert. inventory.quantity represents the current row already stored in the target table.
For the second statement to work, inventory.product_id must have a primary key or a suitable unique constraint. The conflict target identifies the constraint that controls the upsert.
When MERGE is the better fit
Use MERGE when the action depends on more than “did a unique key conflict?”
For example, an inventory synchronization may need to remove products whose quantity becomes zero, update positive quantities, and ignore invalid new products:
MERGE INTO inventory AS t
USING inventory_updates 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);The conditions after WHEN MATCHED and WHEN NOT MATCHED select among actions. PostgreSQL evaluates the clauses in order. Once a source row satisfies a clause, PostgreSQL performs that action and does not try later clauses for that source row.
MERGE can also match on a relationship that is not simply a unique-key conflict. For example, the ON condition could compare a customer code and an effective date range. That flexibility is useful for synchronization jobs, but it also makes the statement easier to misunderstand. Keep the matching rule explicit and test it with representative data.
Concurrency and duplicate source rows
Both statements run as one statement within the transaction, but neither removes the need for correct constraints or source data.
INSERT ... ON CONFLICT is specifically designed for concurrent unique-key upserts. When two transactions try to insert the same new key, PostgreSQL uses the unique constraint to coordinate them. One transaction can insert, while the other handles the conflict according to its DO UPDATE or DO NOTHING clause.
MERGE uses its ON condition to classify candidate rows. A concurrent transaction can change the target after classification. In some race conditions, a unique constraint violation can still occur, especially when two transactions try to insert the same key. If that race matters, enforce the key with a unique constraint and decide whether the application should retry the transaction.
The source must also be suitable for the chosen statement. If multiple source rows match one target row, MERGE can raise a cardinality error because it cannot update or delete the same target row twice in one statement. INSERT ... ON CONFLICT DO UPDATE can likewise fail when duplicate input rows would update the same target row more than once. Deduplicate or aggregate the source before either operation.
> callout warning > A unique constraint protects the target, but it does not make ambiguous source data safe. Make the source contain at most one effective row per key before merging.
A practical rule
Choose INSERT ... ON CONFLICT for a focused key-based upsert. It is shorter, familiar, and optimized for this common workload.
Choose MERGE when the synchronization needs multiple actions, conditional clauses, deletes, or a matching rule that is broader than a unique conflict. On PostgreSQL 17 and later, MERGE also supports WHEN NOT MATCHED BY SOURCE, RETURNING, and merge_action(), which make full synchronization workflows more expressive.
Exercise
You need to add incoming quantities by product key, but you do not need conditional deletes, general join logic, or different actions beyond insert and update. Which statement should you normally choose, and why?
Show answer
Choose INSERT ... ON CONFLICT because it directly expresses a key-based insert-or-update operation and requires less syntax than MERGE.