Sub topic 5
Choosing actions with conditions
This chapter assumes you can write a basic MERGE with WHEN MATCHED and WHEN NOT MATCHED clauses, and that you know NULL comparisons return unknown instead of true or false. It uses PostgreSQL 15 or later. MERGE arrived in version 15.
A plain WHEN MATCHED THEN UPDATE applies the same action to every matched row. Real synchronization jobs need more. Some rows should be deleted, some updated, some ignored, and some inserted only if they pass a check. You get that by adding AND condition to each WHEN clause and by ordering the clauses deliberately.
How a row picks its action
MERGE joins the source to the target using the ON condition. Each joined row falls into one of two situations:
- Matched: a source row found a target row.
- Not matched: a source row found no target row.
PostgreSQL then reads the WHEN clauses for that situation from top to bottom. It runs the first clause whose condition is true and ignores the rest for that row. If no clause qualifies, the row is skipped and nothing happens to it.
Three rules follow from this flow:
- Only one action runs per row, even if several conditions would be true.
- A clause with no
ANDis unconditional. It always qualifies, so it should come last in its group. - A condition that evaluates to
NULLcounts as not true, so the clause does not run and the next one is tried.
Syntax of a conditional clause
Add AND and a Boolean expression between MATCHED (or NOT MATCHED) and THEN:
WHEN MATCHED AND <condition> THEN <action>
WHEN NOT MATCHED AND <condition> THEN <action>The actions available differ by situation. The table also lists what each condition may reference, which is the most common source of errors.
| Clause | Row situation | Columns a condition can use | Actions |
|---|---|---|---|
| `WHEN MATCHED` | Source and target rows both exist | Target and source columns | `UPDATE`, `DELETE`, `DO NOTHING` |
| `WHEN NOT MATCHED` | Only a source row exists | Source columns only | `INSERT`, `DO NOTHING` |
| `WHEN NOT MATCHED BY SOURCE` (PostgreSQL 17+) | Only a target row exists | Target columns only | `UPDATE`, `DELETE`, `DO NOTHING` |
There is no target row to read in a NOT MATCHED clause, so a condition that mentions the target alias there is rejected with an error. The BY SOURCE form is covered in a later chapter.
A worked example
Start with a fresh setup. It resembles the earlier chapters but uses data that exercises every branch.
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),
(3, 'washer', 40);
INSERT INTO inventory_updates (product_id, name, delta) VALUES
(1, 'bolt', NULL),
(2, 'nut', -50),
(3, 'washer', -10),
(4, 'gasket', -5),
(5, 'screw', 30);Each staging row tests a different path:
- Product 1 has an unknown change (
NULL) and should be left alone. - Product 2 would drop to zero and should be deleted.
- Product 3 has a normal decrease and should be updated.
- Product 4 is unknown to the target and has a negative change, so it should not be inserted.
- Product 5 is new with a positive change and should be inserted.
The statement below uses a subquery that aggregates the source to one row per product. The Avoiding the duplicate-source error chapter explains why that matters.
MERGE INTO inventory AS t
USING (
SELECT product_id, max(name) AS name, sum(delta) AS delta
FROM inventory_updates
GROUP BY product_id
) AS s
ON t.product_id = s.product_id
WHEN MATCHED AND s.delta IS NULL THEN
DO NOTHING
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);PostgreSQL reports MERGE 3. The count includes rows inserted, updated, or deleted. It excludes rows handled by DO NOTHING and rows skipped because no clause qualified.
Check the result:
SELECT product_id, name, quantity FROM inventory ORDER BY product_id; product_id | name | quantity
------------+--------+----------
1 | bolt | 100
3 | washer | 30
5 | screw | 30Here is how each row got there:
| Product | Situation | Clause that ran | Result |
|---|---|---|---|
| 1 | Matched, `delta` is `NULL` | `MATCHED AND s.delta IS NULL` | Unchanged |
| 2 | Matched, 50 + (−50) = 0 | `MATCHED AND t.quantity + s.delta <= 0` | Deleted |
| 3 | Matched, 40 + (−10) = 30 | Unconditional `MATCHED` | Updated to 30 |
| 4 | Not matched, `delta` is −5 | None qualified | Skipped |
| 5 | Not matched, `delta` is 30 | `NOT MATCHED AND s.delta > 0` | Inserted |
Why the order matters
Clauses are tested in the order you write them, so the specific cases must come before the general one. Product 1 shows this. If the DO NOTHING clause were missing, its row would reach the delete test. There t.quantity + NULL is NULL, which is not true, so the row would fall through to the unconditional update and try to set quantity to NULL. That violates the NOT NULL constraint and aborts the whole statement.
The reverse mistake is more subtle. Suppose the unconditional update comes first:
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
WHEN MATCHED AND t.quantity + s.delta <= 0 THEN
DELETE;Every matched row qualifies for the first clause, so the DELETE clause is never reached. Rows that should be removed stay behind with a quantity of zero or less. PostgreSQL accepts this statement without a warning, so the only symptom is wrong data. Run the statement against a copy of your data, or review it by reading each group from top to bottom and asking whether any earlier clause can swallow a later one.
Handling NULL in conditions
A condition passes only when it evaluates to true. Both false and NULL fail it and move the row to the next clause. This matters when the source has nullable columns:
s.delta > 0isNULLwhendeltaisNULL, so the row is not inserted.NOT (s.delta > 0)is alsoNULLfor the same row, so you cannot build a safe "everything else" clause by negating a condition.s.delta IS NULLis the reliable way to test for missing values, and it returns true or false.
When you care about unknown values, give them their own clause, as the example does with DO NOTHING. When you do not care, make sure the fall-through clause is safe for NULL input. Alternatively, clean the data in the USING subquery with coalesce, or filter it with a WHERE clause there.
Conditions in ON versus conditions in WHEN
A filter can sit in two places, and the two are not interchangeable. The ON condition decides whether a row is matched. An AND in a WHEN clause decides what to do after that decision.
Suppose you move the positive-delta check into ON:
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id AND s.delta > 0
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);A staging row for an existing product with a negative delta no longer matches, because the join condition is false. It is classified as not matched, and the INSERT clause tries to add a second row for a product that already exists. The primary key rejects it with a unique violation.
Use this rule of thumb:
- Put only the key comparison, the columns that identify a row, in
ON. - Put every "should we act on this row" test in a
WHEN ... ANDcondition. - Put filters that remove source rows entirely in the
USINGsubquery.
Using conditions to compare old and new values
A frequent real-world use is skipping updates that would change nothing. This avoids writing new row versions, firing triggers, and bloating the table:
MERGE INTO inventory AS t
USING (
SELECT product_id, max(name) AS name, sum(delta) AS delta
FROM inventory_updates
GROUP BY product_id
) AS s
ON t.product_id = s.product_id
WHEN MATCHED AND s.delta IS NULL OR s.delta = 0 THEN
DO NOTHING
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);Operator precedence applies inside conditions, as everywhere in SQL. AND binds tighter than OR, so the first clause reads as (MATCHED AND delta IS NULL) OR delta = 0 only in your head. In the grammar, MATCHED AND introduces a single Boolean expression, and s.delta IS NULL OR s.delta = 0 is that whole expression. Wrapping it in parentheses makes your intent plain to readers:
WHEN MATCHED AND (s.delta IS NULL OR s.delta = 0) THEN
DO NOTHINGFor comparing two nullable values, IS DISTINCT FROM treats NULL as an ordinary value. A clause such as WHEN MATCHED AND t.name IS DISTINCT FROM s.name THEN UPDATE SET name = s.name updates only rows whose name has really changed, including changes to or from NULL.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| A `DELETE` or special-case clause never fires | An earlier or unconditional clause matches first | Move specific clauses above general ones |
| Unique violation on a row you thought was an update | A filter in `ON` turned a matched row into a not-matched row | Move the filter into a `WHEN ... AND` condition |
| Error referencing the target alias in a `NOT MATCHED` clause | No target row exists in that situation | Use only source columns, or restructure the source |
| Rows silently ignored | No clause qualified, often because of `NULL` | Add a `NULL`-aware clause or clean the source |
| `NOT NULL` violation during an update | A `NULL` delta fell through to an unconditional update | Add a `DO NOTHING` clause or `coalesce` the value |
Exercise
A MERGE has these clauses, in this order: (1) WHEN MATCHED THEN UPDATE SET quantity = s.delta; (2) WHEN MATCHED AND s.delta = 0 THEN DELETE; (3) WHEN NOT MATCHED THEN INSERT. A matched source row has delta = 0. Which clause runs, and how do you change the statement so that the row is deleted?
Show answer
Clause (1) runs, because it is unconditional and comes first, so the row is updated to quantity 0 and the DELETE clause is never reached. Move the DELETE clause above the UPDATE clause (or add AND s.delta <> 0 to the UPDATE clause) so the specific case is tested first.
Exercise
You write ON t.productid = s.productid AND s.delta > 0 and the statement fails with a unique violation on the primary key when a source row has a negative delta for an existing product. Why does it happen, and what is the fix?
Show answer
The extra test in ON makes the join false for that row, so PostgreSQL treats it as not matched and the WHEN NOT MATCHED THEN INSERT clause tries to insert a duplicate key. Keep only the key comparison in ON, and move the delta test into a WHEN ... AND condition (or filter the source in the USING subquery).