Sub topic 3
Handling Rows That Already Exist
Prerequisites
This chapter assumes that you know basic SELECT, INSERT, UPDATE, and DELETE statements, joins, primary keys, and transactions. It also assumes that you have the inventory and inventory_updates tables from the previous chapter.
A PostgreSQL MERGE statement compares rows from a source with rows in a target table. The ON condition decides whether each source row matches a target row. A matched row is a source row and target row that satisfy this condition.
For an existing target row, use a WHEN MATCHED clause. PostgreSQL added MERGE in version 15.
Updating an existing row
The most common matched action is UPDATE. In this example, an update increases the quantity of an existing product:
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();The target table is inventory, with the alias t. The source table is inventory_updates, with the alias s. When both rows have the same product_id, PostgreSQL updates the target row.
The left side of each assignment names a target column. The right side can refer to both target and source columns. Thus, t.quantity + s.delta means “keep the current target quantity and add the source change.”
A MERGE action runs once for each source-target match. It does not update every target row automatically. A target row is considered only when a source row joins to it.
Deleting or skipping matched rows
A matched row can also be deleted or ignored:
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();The first clause deletes products whose resulting quantity would be zero or negative. The second clause updates all other matched products.
DO NOTHING deliberately skips a matched row:
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED AND s.delta = 0 THEN
DO NOTHING
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now();This leaves the target row unchanged when the source contributes no change. The source row is still processed, but no write occurs.
| Matched action | Result |
|---|---|
| `UPDATE` | Changes columns in the existing target row |
| `DELETE` | Removes the existing target row |
| `DO NOTHING` | Leaves the target row unchanged |
Conditions and clause order
A WHEN MATCHED clause can include an AND condition. PostgreSQL checks the clauses in the order written. For one matched source-target pair, it executes only the first clause whose condition is true.
This ordering matters:
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED AND s.delta < 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now();Here, every negative delta deletes the target row, regardless of the resulting quantity. If the delete clause came after the general update clause, the general clause would match first and the delete would never run.
Put the most specific conditions first and the fallback clause last. You can use several conditional clauses when each action represents a different business rule.
How PostgreSQL chooses an action
The process for a matched source row is:
If no WHEN MATCHED clause applies, PostgreSQL performs no action for that matched row. This is different from an explicit DO NOTHING, but the result is the same for the target table.
A source must not match the same target row more than once. If duplicate source rows join to one target row, PostgreSQL raises a cardinality error instead of applying multiple matched actions unpredictably. Prepare the source with GROUP BY, DISTINCT, or another rule that produces one row per target key.
Exercise
You need to delete an existing product when its incoming delta is negative, but update it for zero or positive deltas. Which WHEN MATCHED clause must come first, and why?
Show answer
Put WHEN MATCHED AND s.delta < 0 THEN DELETE first. PostgreSQL runs only the first matching clause, so placing the general update clause first would prevent the delete clause from being reached.