Sub topic 5
Choosing Actions with Conditions
This chapter assumes PostgreSQL 15 or later, basic SELECT, INSERT, UPDATE, and DELETE, joins, primary keys, and simple transactions. You should also understand table aliases and WHERE conditions.
A MERGE statement classifies each source row by its relationship to the target:
MATCHEDmeans theONcondition found a target row.NOT MATCHEDmeans the source row found no target row.
Each classification can have several WHEN clauses. A condition after WHEN MATCHED or WHEN NOT MATCHED chooses which action applies.
Clause order controls the action
PostgreSQL checks WHEN clauses from top to bottom. For each source row, it runs the first clause whose category and condition match. It does not continue to later clauses after an action runs.
Consider this table setup:
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
(1, 'bolt', -100),
(2, 'nut', 25),
(3, 'washer', 40);This statement deletes a matched product when its new quantity reaches zero or below. It updates other matched products and inserts missing products only when the incoming quantity is positive.
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()
WHEN NOT MATCHED AND s.delta > 0 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
WHEN NOT MATCHED THEN
DO NOTHING;The row for bolt matches and satisfies the first condition, so PostgreSQL deletes it. The row for nut does not satisfy that condition, so PostgreSQL checks the next WHEN MATCHED clause and updates it. The washer row has no target match and a positive delta, so PostgreSQL inserts it.
The final DO NOTHING clause makes the behavior explicit for unmatched rows that fail the positive-delta test. You can omit it when no later action is needed. A DO NOTHING action changes nothing but still counts as the selected action.
Use several conditions for business rules
You can divide rows into multiple actions. Conditions may refer to columns from both the target alias and the source alias.
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED AND s.delta < 0 THEN
UPDATE SET quantity = greatest(t.quantity + s.delta, 0),
updated_at = now()
WHEN MATCHED AND s.delta > 0 THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN MATCHED THEN
DO NOTHING
WHEN NOT MATCHED AND s.delta > 0 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
WHEN NOT MATCHED THEN
DO NOTHING;Here, negative and positive changes use separate matched clauses. A zero delta reaches DO NOTHING. The greatest function prevents a negative result, but it does not delete a product. If deletion is required when the result reaches zero, place a DELETE clause before the update clause.
| Row classification | Condition | Action |
|---|---|---|
| Matched | `t.quantity + s.delta <= 0` | Delete the target row |
| Matched | Otherwise | Update the target row |
| Not matched | `s.delta > 0` | Insert a new row |
| Not matched | Otherwise | Do nothing |
Conditions do not change matching
The ON condition decides whether a row is matched. A WHEN condition only decides what to do after that classification.
For example:
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
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);Changing s.delta = 0 does not turn a matched row into an unmatched row. It only causes the matched row to be skipped.
A common error is placing a filter in ON when it belongs in a WHEN condition. This changes which rows count as matches and may cause an unexpected insert. Keep identity rules, such as t.product_id = s.product_id, in ON. Keep action rules, such as s.delta > 0, in the relevant WHEN clause.
Visualizing the decision
Exercise
A matched row has t.quantity = 10 and s.delta = -10. Which clause must appear before a general WHEN MATCHED THEN UPDATE clause if the row should be removed?
Show answer
WHEN MATCHED AND t.quantity + s.delta <= 0 THEN DELETE must appear first.