Sub topic 4
Inserting Rows That Are Missing with `MERGE`
This chapter assumes that you know basic SELECT, INSERT, UPDATE, and DELETE statements, joins, primary keys, and transactions. You should also be comfortable using table aliases and subqueries.
A common synchronization task is to add rows that exist in a source dataset but do not yet exist in a target table. PostgreSQL's MERGE statement can do this while handling existing rows in the same statement.
What “not matched” means
MERGE compares rows from a source with rows in a target table by using an ON condition. A source row is not matched when no target row satisfies that condition.
For example, suppose both tables identify products with product_id:
| Source row | Target row with same `product_id` | Result |
|---|---|---|
| `(3, 'washer', 40)` | None | Insert the source row |
| `(2, 'nut', 25)` | `(2, 'nut', 50)` | The `WHEN NOT MATCHED` clause does not apply |
The WHEN NOT MATCHED clause describes what to insert for source rows with no target match. PostgreSQL introduced MERGE in PostgreSQL 15.
The basic insert clause
This example creates a target table and a source table. The source contains one existing product and one new product.
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);The following statement inserts only the washer row. The nut row is already matched by product_id. Because this statement has no WHEN MATCHED clause, the matched nut row is skipped.
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);After the statement, the target contains these rows:
| product_id | name | quantity |
|---|---|---|
| 1 | bolt | 100 |
| 2 | nut | 50 |
| 3 | washer | 40 |
The target column list follows INSERT syntax. The expressions in VALUES can refer to columns from the source alias. The target's updated_at column uses its default value because it is not listed.
Adding a condition
You can limit an insert with a condition after WHEN NOT MATCHED. This is useful when the source contains rows that should be ignored.
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN NOT MATCHED AND s.delta > 0 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);Here, a new source row with a nonpositive delta is not inserted. It is skipped because the WHEN condition is false. A false condition does not cause an error or activate another clause unless another applicable WHEN clause exists.
A MERGE can combine this insert action with an update action:
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()
WHEN NOT MATCHED AND s.delta > 0 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);The nut row is updated because it matches. The washer row is inserted because it does not match and has a positive quantity.
Choosing columns and defaults
The source and target do not need to have the same column names or order. Map each target column explicitly:
MERGE INTO inventory AS t
USING (
SELECT product_id, name, delta AS starting_quantity
FROM inventory_updates
) AS s
ON t.product_id = s.product_id
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.starting_quantity);Columns omitted from the INSERT list receive their default values. If a target column is NOT NULL and has no default, the source must provide a value or the statement will fail.
The source can also be a query that filters or transforms rows. This lets you prepare the rows before MERGE, while keeping the target-side action readable.
Exercise
In the example, what happens to a source row (4, 'screw', -5) when the statement uses WHEN NOT MATCHED AND s.delta > 0 THEN INSERT?
Show answer
It is skipped. It is not matched, but the condition is false because -5 is not greater than zero.