Sub topic 3
Handling rows that already exist
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements and join two tables on a condition. It also assumes you know what a primary key is and have a rough idea of how transactions work. MERGE was added in PostgreSQL 15. Everything here runs on 15 or later, and nothing in this chapter needs version 17.
The previous chapter showed the shape of a MERGE statement: a target table, a USING source, and an ON condition. This chapter covers the WHEN MATCHED branch, which handles rows where the ON condition found a partner. Rows with no partner are the subject of the next chapter.
What "matched" means
MERGE joins the source to the target using the ON condition. Each source row then falls into one of two groups:
- Matched: at least one target row satisfies the
ONcondition for this source row. - Not matched: no target row satisfies it.
A WHEN MATCHED clause says what to do with the matched group. It offers three actions:
| Action | Effect on the matched target row |
|---|---|
| `UPDATE SET ...` | Changes columns of the target row. |
| `DELETE` | Removes the target row. |
| `DO NOTHING` | Leaves the target row alone. |
You cannot INSERT in a WHEN MATCHED clause. The row already exists, so insertion belongs to the WHEN NOT MATCHED branch.
Setup
These are the tables from the topic's running example. Run them once. Every later example uses a transaction that ends in ROLLBACK, so the data stays the same between examples.
CREATE TABLE inventory (
product_id int PRIMARY KEY,
name text NOT NULL,
quantity int NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE inventory_updates (
product_id int,
name text,
delta int
);
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);Product 2 exists in both tables, so it is matched. Product 3 exists only in the source. Product 1 exists only in the target.
Updating matched rows
WHEN MATCHED THEN UPDATE SET takes a list of assignments. The right side of each assignment can use columns from both the target and the source.
BEGIN;
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();
SELECT product_id, name, quantity FROM inventory ORDER BY product_id;
ROLLBACK;psql prints the command tag MERGE 1 for the MERGE statement. The SELECT then returns this:
product_id | name | quantity
------------+------+----------
1 | bolt | 100
2 | nut | 75Three things happened:
- Product 2 matched, so its quantity became 50 + 25 = 75.
- Product 3 matched nothing. This statement has no
WHEN NOT MATCHEDclause, so the washer row is ignored and not inserted. - Product 1 never appeared in the source, so it is untouched.
A MERGE with only WHEN MATCHED clauses is valid. It works like an UPDATE ... FROM that also lets you branch on conditions.
Rules for the SET list
- Left side: bare column names. Write
SET quantity = ..., notSET t.quantity = .... The qualified form is a syntax error. The target is already known. - Right side: qualify anything ambiguous. Both tables have
product_id, so an unqualifiedproduct_idinONor in an expression fails withcolumn reference "product_id" is ambiguous. Always use the aliasestands. - Computed values are fine. Any expression is allowed, including function calls,
CASE, and scalar subqueries. DEFAULTis allowed.SET updated_at = DEFAULTresets a column to its declared default.- Unlisted columns keep their old values. In the example,
nameis not in theSETlist, so it stays as it was.
Unlike a plain UPDATE, the SET list cannot assign to the target's system columns or to columns of the source. It only changes target columns.
Deleting matched rows
DELETE takes no arguments. It removes the matched target row.
CREATE TABLE discontinued (
product_id int PRIMARY KEY
);
BEGIN;
INSERT INTO discontinued (product_id) VALUES (1);
MERGE INTO inventory AS t
USING discontinued AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
DELETE;
SELECT product_id, name FROM inventory ORDER BY product_id;
ROLLBACK;The tag is MERGE 1, and only product 2 remains. Because MERGE only deletes rows that matched, you can feed it a long list of discontinued products, and any ids that are not in inventory are silently skipped. A plain DELETE ... USING behaves the same way, but MERGE lets you put the delete beside other actions in one statement, as the next section shows.
Skipping matched rows with DO NOTHING
DO NOTHING looks useless at first, because a matched row that has no clause is skipped anyway. It earns its place through clause ordering.
Within one MERGE, you can write several WHEN MATCHED clauses. For each matched row, PostgreSQL checks the clauses from top to bottom and runs the first one whose condition is true. It runs at most one action per row. A DO NOTHING clause placed early lets you intercept rows that a later, more general clause would otherwise change.
Here is a source that includes a no-op row for the bolt:
BEGIN;
INSERT INTO inventory_updates (product_id, name, delta) VALUES (1, 'bolt', 0);
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();
ROLLBACK;The tag is MERGE 1. The nut row was updated, and the bolt row was skipped by the first clause. Remove the first clause and the tag becomes MERGE 2, because the bolt row would be rewritten with the same quantity.
That second case matters in practice. In PostgreSQL, an UPDATE that changes nothing still writes a new row version. It also fires row-level triggers, and it leaves behind a dead row version that VACUUM must clean up later. Skipping rows that would not change is cheaper on large tables.
The AND s.delta = 0 part is a clause condition. The next chapters cover conditions in depth. For now, treat the condition as an extra filter on when the clause applies.
Counting results
The command tag MERGE n reports the total number of rows inserted, updated, or deleted. Rows handled by DO NOTHING, and rows that match no clause, are not counted. A tag of MERGE 0 therefore means no row changed. It does not tell you how many source rows were examined.
Combining UPDATE and DELETE in one pass
Several WHEN MATCHED clauses can use different actions. This example removes products whose stock would drop to zero or below and updates the rest:
BEGIN;
INSERT INTO inventory_updates (product_id, name, delta) VALUES (1, 'bolt', -100);
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();
SELECT product_id, quantity FROM inventory ORDER BY product_id;
ROLLBACK;The bolt row has 100 in stock and a delta of -100, so the first clause deletes it. The nut row fails the first condition and falls through to the second clause, which raises it to 75. The result is MERGE 2 and a single row left in inventory.
Order matters. If you swap the two clauses, the unconditional UPDATE catches every matched row, and the DELETE never runs. PostgreSQL does not warn you about this. When a MERGE seems to ignore one of its clauses, check the order first.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `syntax error` near `SET t.quantity` | Target column qualified on the left of `SET`. | Write `SET quantity = ...`. |
| `column reference "product_id" is ambiguous` | An unqualified column exists in both tables. | Prefix with `t.` or `s.`. |
| `MERGE command cannot affect row a second time` | Two source rows matched the same target row. | Deduplicate or aggregate the source. The chapter on source cardinality covers this. |
| A `DELETE` clause never fires | An earlier unconditional `WHEN MATCHED` clause takes every matched row. | Put the more specific clause first. |
| `MERGE 0` when you expected changes | The `ON` condition matched nothing, for example because of `NULL` keys or mismatched types. | Run the source and target as a plain `SELECT ... JOIN` with the same `ON` condition and inspect it. |
| Running the same `MERGE` twice doubles the change | `quantity = t.quantity + s.delta` is not idempotent. | Load each batch once, or make the source carry absolute values. |
NULL keys never match
The ON condition uses ordinary SQL equality. If t.product_id = s.product_id is evaluated with a NULL on either side, the result is unknown and the rows do not match. A source row with a NULL key is therefore always treated as not matched. If you need NULL = NULL to count as a match, write t.key IS NOT DISTINCT FROM s.key. Be aware that this form usually cannot use a plain index, which affects performance.
Locking and concurrent changes
When a matched row is updated or deleted, PostgreSQL locks it, just as UPDATE and DELETE do. If another transaction has already changed that row and not yet committed, MERGE waits. How it then behaves depends on the isolation level, and the concurrency chapter covers that. For now, remember that a MERGE that updates many rows holds many row locks until the transaction ends. Keep such statements in short transactions.
Choosing between UPDATE, DELETE, and DO NOTHING
- Use
UPDATEwhen the source carries new values for rows you want to keep. - Use
DELETEwhen the presence of a source row means "this record should go away", such as a list of discontinued ids. - Use
DO NOTHINGas a guard placed before a broader clause. It keeps unchanged rows out of the write path. - Combine several
WHEN MATCHEDclauses when different rows need different treatment, and put the most specific condition first.
Exercise
The table inventory holds product 2 with quantity 75. The table inventory_updates now holds the single row (2, 'nut', 0). You run a MERGE with WHEN MATCHED AND s.delta = 0 THEN DO NOTHING followed by WHEN MATCHED THEN UPDATE SET quantity = t.quantity + s.delta. What command tag does psql print, and why? What would it print if the DO NOTHING clause were removed?
Show answer
It prints MERGE 0. The row matches, but the first clause with a true condition is DO NOTHING, and rows handled by DO NOTHING are not counted. Without that clause, the unconditional UPDATE runs and rewrites the row with the same quantity, so the tag would be MERGE 1, and the row would get a new version, fire its triggers, and leave a dead tuple.
Exercise
Write a MERGE that deletes from inventory every product whose id appears in discontinued, and also sets quantity to 0 for every product that appears in inventory_updates with a delta below -1000, without deleting those. Why does this need two statements, and not one MERGE with two WHEN MATCHED clauses?
Show answer
A single MERGE has one USING source, so it cannot read both discontinued and inventory_updates unless you combine them into one subquery. Using two statements is simpler: MERGE INTO inventory AS t USING discontinued AS s ON t.product_id = s.product_id WHEN MATCHED THEN DELETE; and MERGE INTO inventory AS t USING inventory_updates AS s ON t.product_id = s.product_id WHEN MATCHED AND s.delta < -1000 THEN UPDATE SET quantity = 0;. You could merge them into one statement with a UNION ALL subquery that has a column marking the reason, but that is harder to read.