Sub topic 1
Why MERGE exists
Prerequisites
This chapter assumes that you can write basic SELECT, INSERT, UPDATE, and DELETE statements. You should also understand joins, primary keys, unique constraints, subqueries, aliases, and the basics of transactions.
The synchronize-or-upsert problem
Applications often receive a set of changes and must apply them to an existing table. For each incoming row, the application may need to:
- Update a row that already exists.
- Insert a row that is missing.
- Delete a row when a business rule says it is no longer valid.
- Skip a row that does not meet a condition.
This is a synchronization problem. The incoming rows are the source, and the table being changed is the target.
Before MERGE, developers commonly used separate statements:
UPDATE inventory
SET quantity = quantity + 25
WHERE product_id = 2;
INSERT INTO inventory (product_id, name, quantity)
SELECT 3, 'washer', 40
WHERE NOT EXISTS (
SELECT 1
FROM inventory
WHERE product_id = 3
);This approach repeats the matching logic. It can also create a race between statements. Another transaction may insert product 3 after the NOT EXISTS check but before the INSERT. A unique constraint can protect the table, but the application still has to handle the resulting error or retry.
MERGE expresses the comparison and the possible actions as one statement.
What MERGE adds
PostgreSQL introduced MERGE in PostgreSQL 15. A MERGE statement compares rows from a source with rows in a target using an ON condition. It then chooses an action for each source row.
The main structure is:
MERGE INTO target AS t
USING source AS s
ON matching_condition
WHEN MATCHED THEN
UPDATE ...
WHEN NOT MATCHED THEN
INSERT ...;WHEN MATCHED applies when the ON condition finds a target row. WHEN NOT MATCHED applies when the source row has no matching target row.
The following runnable example updates the existing product and inserts the new product:
CREATE TEMP TABLE inventory (
product_id integer PRIMARY KEY,
name text NOT NULL,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TEMP TABLE inventory_updates (
product_id integer,
name text,
delta integer
);
INSERT INTO inventory (product_id, name, quantity)
VALUES (1, 'bolt', 100), (2, 'nut', 50);
INSERT INTO inventory_updates (product_id, name, delta)
VALUES (2, 'nut', 25), (3, 'washer', 40);
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);After the statement, product 2 has quantity 75, and product 3 has quantity 40.
The target and source do not need to be physical tables. The source can also be a query, a view, or a derived table. This lets you clean, filter, or aggregate incoming data before matching it.
A single decision for each source row
The matching process can be viewed as a decision:
This model is useful because it separates two concerns:
- The
ONcondition identifies the relationship between source and target rows. - The
WHENclauses decide what to do after that relationship is known.
A MERGE statement can include several WHEN clauses. For example, a matched row could be deleted when its resulting quantity would be zero, and updated otherwise. Conditions on the clauses make those choices explicit. Later chapters cover clause ordering and source preparation in detail.
MERGE compared with older patterns
MERGE is broader than a simple upsert. An upsert is an operation that inserts a row or updates it when a conflict occurs. PostgreSQL also supports upserts with INSERT ... ON CONFLICT.
| Requirement | `MERGE` | `INSERT ... ON CONFLICT` |
|---|---|---|
| Insert missing rows | Yes | Yes |
| Update existing rows | Yes | Yes |
| Delete matched rows | Yes | No |
| Multiple conditional actions | Yes | More limited |
| Requires a unique conflict target | Not always, but usually wise | Yes for conflict handling |
Choose INSERT ... ON CONFLICT when the task is simply “insert these rows, or update conflicting rows.” Choose MERGE when the operation needs several actions, source-based conditions, or deletion as part of synchronization.
MERGE still needs careful design. The source must not contain multiple rows that match the same target row. A later chapter explains that cardinality rule and how to prevent its errors.
Exercise
Which part of a MERGE statement determines whether a source row is matched or not matched?
Show answer
The ON condition determines whether the source row finds a target row. WHEN MATCHED and WHEN NOT MATCHED then choose the action.