Sub topic 9
Deleting or updating rows missing from the source (PostgreSQL 17)
This chapter assumes you can write a basic MERGE with WHEN MATCHED and WHEN NOT MATCHED, and that you know how the ON condition joins source to target. PostgreSQL 15 introduced MERGE. PostgreSQL 17 added WHEN NOT MATCHED BY SOURCE, which handles target rows that have no partner in the source. On PostgreSQL 15 or 16 the statements in this chapter fail with a syntax error.
The gap in earlier MERGE statements
A MERGE in PostgreSQL 15 or 16 can only act on two kinds of rows:
- Rows in both source and target (
WHEN MATCHED). - Rows only in the source (
WHEN NOT MATCHED).
Rows that exist only in the target were invisible to it. To mirror a full snapshot, such as a nightly supplier feed, you needed a second statement:
DELETE FROM price_list AS t
WHERE t.supplier = 'acme'
AND NOT EXISTS (SELECT 1 FROM supplier_feed AS s WHERE s.sku = t.sku);Two statements mean two scans, and unless both run in one transaction, a window where the table is half synchronized. PostgreSQL 17 folds this into the same MERGE.
The three row categories
Think of MERGE as a full outer join between the source and the target. Every joined row falls into exactly one category, and each category has its own set of WHEN clauses.
WHEN NOT MATCHED without further words has always meant "not matched by target". PostgreSQL 17 lets you write it explicitly as WHEN NOT MATCHED BY TARGET. The two forms are identical, and the explicit one reads better next to BY SOURCE.
Syntax and rules
WHEN NOT MATCHED BY SOURCE [ AND condition ] THEN
{ UPDATE SET column = expression [, ...] | DELETE | DO NOTHING }The rules that follow from the row categories:
- A target-only row has no source row, so the clause cannot use
INSERT. - For the same reason, the
AND conditionand theUPDATE SETexpressions can reference only target columns. Referencing a source column is an error, because that row has no source columns to read. - A statement can contain several
WHEN NOT MATCHED BY SOURCEclauses, each with its own condition. - If no clause applies to a row, the row is left alone.
A worked example: mirroring a supplier feed
The setup below has a price list shared by several suppliers. A feed arrives from one supplier, acme, and contains that supplier's full current catalog.
CREATE TABLE price_list (
sku text PRIMARY KEY,
supplier text NOT NULL,
price numeric(10,2) NOT NULL,
active boolean NOT NULL DEFAULT true
);
CREATE TABLE supplier_feed (
sku text PRIMARY KEY,
price numeric(10,2) NOT NULL
);
INSERT INTO price_list (sku, supplier, price) VALUES
('A1', 'acme', 10.00),
('A2', 'acme', 20.00),
('A3', 'acme', 30.00),
('B1', 'bolt co', 5.00);
INSERT INTO supplier_feed (sku, price) VALUES
('A2', 21.00),
('A3', 30.00),
('A4', 40.00);The goal is for the active acme rows to match the feed exactly. Rows that left the feed are deactivated instead of deleted, so history survives. Other suppliers must not be touched.
MERGE INTO price_list AS t
USING supplier_feed AS s
ON t.sku = s.sku
WHEN MATCHED AND (t.price IS DISTINCT FROM s.price OR NOT t.active) THEN
UPDATE SET price = s.price, active = true
WHEN NOT MATCHED BY TARGET THEN
INSERT (sku, supplier, price)
VALUES (s.sku, 'acme', s.price)
WHEN NOT MATCHED BY SOURCE AND t.supplier = 'acme' AND t.active THEN
UPDATE SET active = false;Here is what each row does:
| sku | Category | Result |
|---|---|---|
| A1 | Target only, supplier `acme`, active | Deactivated (`active = false`) |
| A2 | Matched, price differs | Price becomes 21.00 |
| A3 | Matched, price and active flag unchanged | No clause applies, row skipped |
| A4 | Source only | Inserted with supplier `acme` |
| B1 | Target only, supplier `bolt co` | Condition is false, row left alone |
The t.supplier = 'acme' test is what scopes the statement. Without it, B1 would also be deactivated, because it is absent from the acme feed.
The IS DISTINCT FROM test in the matched clause avoids rewriting rows whose values did not change. That keeps write volume and dead tuples down.
Scope the clause with a condition, not the ON clause
It is tempting to restrict the target by adding AND t.supplier = 'acme' to the ON condition. That does not do what you might expect. A target row that fails the ON condition simply has no partner, so it counts as not matched by source. The test then widens the set of rows that WHEN NOT MATCHED BY SOURCE sees instead of narrowing it. Put the filter in the AND condition of the WHEN NOT MATCHED BY SOURCE clause itself.
Several clauses for one category
Clauses of one category are tried in order, and the first one whose condition is true runs. This lets you apply a different action to different leftover rows:
MERGE INTO price_list AS t
USING supplier_feed AS s
ON t.sku = s.sku
WHEN MATCHED THEN
UPDATE SET price = s.price, active = true
WHEN NOT MATCHED BY TARGET THEN
INSERT (sku, supplier, price)
VALUES (s.sku, 'acme', s.price)
WHEN NOT MATCHED BY SOURCE AND t.supplier = 'acme' AND NOT t.active THEN
DELETE
WHEN NOT MATCHED BY SOURCE AND t.supplier = 'acme' THEN
UPDATE SET active = false;A row that is already inactive and still missing from the feed is deleted. An active one is deactivated first. So a SKU must be absent from the feed in two successive runs before it is removed.
Order matters when conditions overlap. If you swapped the two last clauses, the unconditional-looking UPDATE clause would catch every acme row, and the DELETE clause would never run.
The dangerous case: a partial source
WHEN NOT MATCHED BY SOURCE treats the source as the complete truth for the scope you chose. If the source is incomplete, the statement deletes or deactivates valid rows.
Consider the inventory_updates table from earlier in this tutorial. It holds changes to apply, not a full snapshot. This statement is valid on PostgreSQL 17:
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 NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;With the sample data, bolt (product 1) has no row in inventory_updates, so it is deleted, even though nothing was wrong with it. The statement is correct SQL and does exactly what it says. The mistake is using a delta table as if it were a snapshot.
Use WHEN NOT MATCHED BY SOURCE only when the source is a full picture of the slice of the target you named in the condition.
Seeing what happened with RETURNING
PostgreSQL 17 also lets MERGE return rows. The function merge_action() reports which action ran for each one. This is the fifth example in the plan, applied to inventory:
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 NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
RETURNING merge_action() AS action, t.product_id, t.quantity;On the sample data the result contains three rows, in no guaranteed order:
| action | product_id | quantity |
|---|---|---|
| UPDATE | 2 | 75 |
| INSERT | 3 | 40 |
| DELETE | 1 | 100 |
For UPDATE and INSERT, the returned columns are the new values. For DELETE, they are the values the row had before it was removed, which is why product 1 shows quantity 100. Use this output to log or audit exactly what a synchronization changed. The next chapter covers RETURNING in more detail.
Triggers, constraints and concurrency
- Row-level triggers fire for the rows that
WHEN NOT MATCHED BY SOURCEupdates or deletes, just as for any otherUPDATEorDELETE. - Foreign keys apply. Deleting a target row that other tables reference fails, or cascades, according to the constraint.
- Concurrency rules are the same as for the rest of
MERGE. AtREAD COMMITTED, a target row that another transaction changes while your statement runs is re-checked against your clause conditions. Rows another transaction inserts after your statement starts are not seen. They are not mistaken for "missing from source", but they are not synchronized either.
Performance
A statement without NOT MATCHED BY SOURCE can often probe the target through an index, once per source row. With it, MERGE must find every target row that has no partner. In practice the planner has to read the target in full, or at least the part that can satisfy your conditions, and join it to the source with a hash or merge join. Consider these points:
- Index the join column on both sides, as for any
MERGE. The primary key onskuserves the target here. - Expect a cost proportional to the target size, not the source size. A 1,000-row feed merged into a 50-million-row table still reads the target.
- If the scope is a small slice of a very large table, a separate
DELETE ... WHERE NOT EXISTSrestricted by an indexed column can be cheaper. Compare withEXPLAIN (ANALYZE)on realistic data rather than assuming. - Partitioning by the scoping column (for example, supplier) lets the statement work on one partition when the target is a partition.
Summary of the decision
| Situation | Approach |
|---|---|
| Source holds changes only (deltas, events) | No `BY SOURCE` clause |
| Source is a full snapshot of the whole target | `WHEN NOT MATCHED BY SOURCE THEN DELETE` |
| Source is a full snapshot of one slice | Add the slice test to the `BY SOURCE` condition |
| You must keep history | `UPDATE SET active = false` or a deleted-at timestamp instead of `DELETE` |
| PostgreSQL 15 or 16 | Separate `DELETE ... WHERE NOT EXISTS` in the same transaction |
Exercise
A table price_list holds rows for several suppliers. You load a full feed for supplier 'acme' into supplier_feed and run a MERGE with WHEN NOT MATCHED BY SOURCE THEN DELETE and no extra condition. What happens to the rows of supplier 'bolt co', and how do you fix the statement?
Show answer
Rows for 'bolt co' are deleted, because none of them appear in the 'acme' feed, so they are not matched by source. Fix it by adding a condition to the clause: WHEN NOT MATCHED BY SOURCE AND t.supplier = 'acme' THEN DELETE. Putting the filter in the ON clause would not help, because target rows failing ON are also treated as not matched by source.
Exercise
Why does this clause fail: WHEN NOT MATCHED BY SOURCE AND s.price > 10 THEN UPDATE SET active = false?
Show answer
A row that is not matched by source has no source row, so the condition cannot reference the source alias s. Conditions and SET expressions in this clause may use only target columns, for example t.price > 10.
Exercise
After running a MERGE with WHEN NOT MATCHED BY SOURCE THEN DELETE ... RETURNING merge_action(), t.quantity, a deleted row shows quantity 100. Is that the new or the old value, and why?
Show answer
It is the old value. A deleted row has no new state, so RETURNING reports the values the row had just before it was removed.