Sub topic 9
Deleting or Updating Rows Missing from the Source (PostgreSQL 17)
This chapter assumes you know basic SELECT, INSERT, UPDATE, and DELETE statements, joins, primary keys, and transactions. You should also understand that a MERGE compares rows from a source relation with rows in a target table using an ON condition.
PostgreSQL 17 adds WHEN NOT MATCHED BY SOURCE. This clause handles target rows for which no source row satisfies the ON condition. It is useful when the source represents the current complete state and the target must be synchronized with it.
How “missing from the source” works
A normal WHEN NOT MATCHED clause means that a source row has no matching target row. It can insert that source row.
WHEN NOT MATCHED BY SOURCE means the reverse: a target row has no matching source row. It can update, delete, or skip that target row.
The direction matters:
| Clause | Row with no match | Typical action |
|---|---|---|
| `WHEN NOT MATCHED` | Source row | Insert into target |
| `WHEN NOT MATCHED BY SOURCE` | Target row | Delete or mark inactive |
Consider a target table containing all products currently listed in an application. The source table contains products received from a fresh import. If a target product is absent from the import, the import may indicate that the product was removed. PostgreSQL 17 lets one MERGE mark that product inactive.
Updating rows missing from the source
A common choice is a soft delete. Instead of physically removing a row, update a flag such as active or record a timestamp. This preserves history and makes accidental source omissions easier to recover.
The following example starts with a target table and a source table. The source contains products that should remain active. Product 2 is absent from the source, so it is marked inactive.
CREATE TABLE products (
product_id integer PRIMARY KEY,
name text NOT NULL,
active boolean NOT NULL DEFAULT true
);
CREATE TABLE current_products (
product_id integer PRIMARY KEY,
name text NOT NULL
);
INSERT INTO products (product_id, name) VALUES
(1, 'bolt'),
(2, 'nut'),
(3, 'washer');
INSERT INTO current_products (product_id, name) VALUES
(1, 'bolt'),
(3, 'washer');
MERGE INTO products AS target
USING current_products AS source
ON target.product_id = source.product_id
WHEN MATCHED THEN
UPDATE SET name = source.name,
active = true
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET active = false;After the statement, products 1 and 3 are active. Product 2 remains in the table but has active = false.
WHEN NOT MATCHED BY SOURCE does not require a source alias in its action because there is no matching source row. For example, source.name would be NULL in this branch and should not be used as though a source row existed.
Deleting rows missing from the source
If the target is only a disposable working table, you can delete rows that are absent from the source.
MERGE INTO products AS target
USING current_products AS source
ON target.product_id = source.product_id
WHEN NOT MATCHED BY SOURCE THEN
DELETE;This removes target products 2 and any other target rows not represented by current_products. Use this form only when the source is a complete authoritative list. If the source is a partial export, temporary outage, or filtered report, deletion could remove valid data.
Conditions and clause order
You can add an AND condition to limit which missing target rows are changed. For example, delete only inactive products that have been missing from the source after a separate status update:
MERGE INTO products AS target
USING current_products AS source
ON target.product_id = source.product_id
WHEN NOT MATCHED BY SOURCE
AND target.active = false THEN
DELETE;A MERGE evaluates its WHEN clauses in order for each candidate row. Once a row satisfies a clause and that clause performs an action, later clauses are not used for that row. Put more specific conditions before broader conditions.
You can combine all three directions in one statement:
MERGE INTO products AS target
USING current_products AS source
ON target.product_id = source.product_id
WHEN MATCHED THEN
UPDATE SET name = source.name,
active = true
WHEN NOT MATCHED THEN
INSERT (product_id, name, active)
VALUES (source.product_id, source.name, true)
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET active = false;This statement refreshes existing products, inserts new products, and deactivates products missing from the current snapshot.
Version and safety checks
WHEN NOT MATCHED BY SOURCE is available in PostgreSQL 17 and later. On older versions, perform the equivalent operation with a separate UPDATE or DELETE using NOT EXISTS:
UPDATE products AS target
SET active = false
WHERE NOT EXISTS (
SELECT 1
FROM current_products AS source
WHERE source.product_id = target.product_id
);The ON condition should use the target's primary key or another appropriate unique key. An incorrect condition can classify valid rows as missing or match unrelated rows.
Exercise
In a PostgreSQL 17 MERGE, which clause handles a target row that has no matching source row, and when is DELETE unsafe?
Show answer
WHEN NOT MATCHED BY SOURCE handles it. DELETE is unsafe when the source is not a complete authoritative snapshot, because omitted rows may still be valid.