Sub topic 11
INSERT ON CONFLICT versus MERGE
This chapter assumes you know basic SELECT, INSERT, and UPDATE, primary keys, unique constraints, and how to run PostgreSQL statements from psql or another client. The examples use PostgreSQL 15 or later, because MERGE was introduced in PostgreSQL 15.
Both INSERT ... ON CONFLICT and MERGE can synchronize incoming data with an existing table. They differ in how they detect matches, how they handle conflicts, and how directly they express an upsert.
The two statements
INSERT ... ON CONFLICT starts with an insert. If a unique constraint or unique index detects a conflict, PostgreSQL takes the alternative action you specify:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();The conflict target, (sku), identifies the unique rule that detects an existing row. EXCLUDED represents the row proposed by the INSERT.
MERGE starts with a source relation and a join condition. It then chooses an action for each source row:
MERGE INTO product_stock AS target
USING (
VALUES ('A-100', 5)
) AS source(sku, quantity)
ON target.sku = source.sku
WHEN MATCHED THEN
UPDATE SET
quantity = source.quantity,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (sku, quantity)
VALUES (source.sku, source.quantity);Here, target.sku = source.sku determines whether a target row matches. WHEN MATCHED handles existing rows, and WHEN NOT MATCHED handles new rows.
Compare their decision models
| Feature | `INSERT ... ON CONFLICT` | `MERGE` |
|---|---|---|
| Main starting point | An insert proposal | A source-to-target match |
| Conflict or match rule | Unique constraint or index | Boolean `ON` condition |
| Actions | Do nothing or update | Multiple conditional actions |
| Best fit | Atomic single-key upserts | More complex synchronization rules |
| PostgreSQL version | Available before PostgreSQL 15 | PostgreSQL 15 and later |
ON CONFLICT is usually the clearest choice when the requirement is simple: insert this row, or update the row with the same unique key.
MERGE is useful when one source row can require different actions, such as updating a match, inserting a non-match, or deleting a match that meets an additional condition. A MERGE statement can contain several WHEN clauses, evaluated in order.
Concurrency behavior
A common but unsafe upsert pattern is:
SELECT 1
FROM product_stock
WHERE sku = 'A-100';
-- If no row was found:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5);Two transactions can both run the SELECT before either transaction inserts. They both see no row, and one insert then fails with a unique-constraint error. Adding a transaction does not automatically remove this race.
INSERT ... ON CONFLICT uses the unique index as part of one atomic statement. PostgreSQL coordinates concurrent writers that propose the same key. One statement can insert the row, while another waits and then performs its conflict action against the resulting row.
MERGE uses its ON condition to classify rows as matched or not matched. Under concurrent writes, a source row classified as not matched can encounter a unique constraint violation when it tries to insert a row that another transaction inserted meanwhile. Therefore, MERGE does not provide the same conflict-handling guarantee as ON CONFLICT for a straightforward unique-key upsert.
> callout note > Use ON CONFLICT when concurrent writers may propose the same unique key and the desired behavior is specifically “insert or update.” Choose MERGE for its richer action logic, not as a general replacement for ON CONFLICT.
Choosing between them
Choose INSERT ... ON CONFLICT when:
- A unique constraint or unique index defines the identity of a row.
- You need
DO NOTHINGor oneDO UPDATEaction. - You need conflict-safe behavior under concurrent writers.
- You want to use
RETURNINGto inspect inserted or updated rows.
Choose MERGE when:
- The source is a query or staging table containing many rows.
- Matching uses a condition that is not naturally an insert conflict target.
- You need several ordered
WHEN MATCHEDorWHEN NOT MATCHEDbranches. - Your application can handle unique violations caused by concurrent inserts, or it protects the operation with an appropriate transaction and retry strategy.
For example, MERGE can apply different updates based on source data:
MERGE INTO product_stock AS target
USING stock_changes AS source
ON target.sku = source.sku
WHEN MATCHED AND source.quantity = 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE SET
quantity = source.quantity,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (sku, quantity)
VALUES (source.sku, source.quantity);The key distinction is that ON CONFLICT delegates identity to a unique index and has specialized atomic conflict handling. MERGE gives you a general matching-and-action framework, but its match decision and its later write are separate concerns under concurrency.
Exercise
You need to insert customer records by unique email, update an existing customer's name, and safely handle two concurrent requests for the same email. Should you start with INSERT ... ON CONFLICT or MERGE, and why?
Show answer
Use INSERT ... ON CONFLICT. The unique email rule defines the conflict target, and PostgreSQL provides atomic conflict handling for concurrent writers. MERGE would be preferable only if the synchronization required multiple conditional actions.