Sub topic 4
Inserting rows that are missing
This chapter covers the WHEN NOT MATCHED clause of MERGE: how it decides which source rows count as missing, what its INSERT action allows, and how it fails. It assumes you know INSERT, joins, primary keys, and the basic shape of a MERGE statement (target, USING source, ON condition). MERGE requires PostgreSQL 15 or later.
What "not matched" means
MERGE joins the source to the target using the ON condition. A source row is not matched when no target row satisfies that condition. WHEN NOT MATCHED is the branch that runs for those rows, and it supports exactly one real action: INSERT. You cannot update or delete here, because there is no target row to act on.
The decision is made per source row, against the target as it looked when the statement started. This has two consequences that matter later:
- Rows the statement inserts are not visible to its own join. Two source rows with the same new key are both "not matched".
- The statement never needs a unique index to decide what is missing. It only needs the
ONcondition to be false for every target row.
flowchart TDReplace the placeholder above with the real diagram below.
A minimal insert-only MERGE
Start from the tables used throughout this tutorial.
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);This statement adds products that are missing and leaves existing ones alone:
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);PostgreSQL reports MERGE 1. Product 3 (washer) had no match, so it was inserted with quantity 40. Product 2 matched, and because there is no WHEN MATCHED clause, nothing happened to it. The updated_at column was not listed, so it took its default, now().
Run the same statement again and it reports MERGE 0. Every source row now matches, so the statement is idempotent: running it twice gives the same result as running it once. That property is the main reason to write insert-only merges.
The INSERT action in detail
The INSERT inside MERGE looks like a normal INSERT, with these differences.
No table name and no SELECT. The target is already known. You supply a column list and a single VALUES row, or DEFAULT VALUES. One source row produces at most one inserted row.
Values may only refer to the source. In VALUES (...) you can use source columns, constants, functions, and DEFAULT. You cannot refer to target columns such as t.quantity, because the target has no row for this source row. The column list also takes bare column names, with no t. prefix.
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, updated_at)
VALUES (s.product_id, upper(s.name), GREATEST(s.delta, 0), DEFAULT);Omitted columns get their defaults. If you leave out the column list, the values map to the target's columns in table order, which breaks silently when someone adds a column. Always list the columns.
DEFAULT VALUES is allowed. It inserts a row made only of column defaults. This is only useful when the table has defaults for every column, so it is rare.
Identity columns follow the usual rules. Inserting an explicit value into a GENERATED ALWAYS identity column fails unless you add OVERRIDING SYSTEM VALUE after the column list. OVERRIDING USER VALUE ignores the supplied value and uses the generated one.
CREATE TABLE customer (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE
);
CREATE TEMP TABLE incoming_customer (email text);
INSERT INTO incoming_customer VALUES ('[email protected]'), ('[email protected]');
MERGE INTO customer AS t
USING incoming_customer AS s
ON t.email = s.email
WHEN NOT MATCHED THEN
INSERT (email) VALUES (s.email);Here id is omitted, so the identity sequence supplies it.
Conditions and multiple NOT MATCHED clauses
A WHEN NOT MATCHED clause can carry an extra condition with AND. The condition may use only source columns. Referencing target columns in it raises an error, for the same reason they cannot appear in VALUES.
You may write several WHEN NOT MATCHED clauses. PostgreSQL checks them in the order written and uses the first one whose condition is true. The action DO NOTHING lets you say "skip these rows" explicitly:
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)
WHEN NOT MATCHED THEN
DO NOTHING;A source row with a zero or negative delta and no matching product would create a product with a nonsensical quantity, so the condition filters it out. The final DO NOTHING clause changes no behavior, since unhandled rows are ignored anyway. It documents the intent for the next reader. Order matters: if you put the unconditional clause first, it would catch every row and the conditional one would never run.
Combining insert with the earlier chapters' clauses gives the full pattern from the plan:
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 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 MATCHED and WHEN NOT MATCHED branches never compete. A given source row goes to one side or the other.
NOT MATCHED BY TARGET (PostgreSQL 17)
PostgreSQL 17 added WHEN NOT MATCHED BY SOURCE for target rows that have no source row. To keep the two readable side by side, it also accepts BY TARGET as an explicit spelling:
WHEN NOT MATCHED BY TARGET THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)WHEN NOT MATCHED and WHEN NOT MATCHED BY TARGET mean the same thing. Use the longer form on 17 and later if the statement also has a BY SOURCE clause. On versions 15 and 16, only the short form is valid.
Failure modes
Duplicate new keys in the source
MERGE raises its "cannot affect row a second time" error only when several source rows match the same target row. Source rows that match nothing do not trigger it. Two source rows with the same new key are both inserted, and a unique constraint on the target then rejects the second one.
CREATE TABLE tag (
name text PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TEMP TABLE incoming_tag (name text);
INSERT INTO incoming_tag VALUES ('sql'), ('sql'), ('postgres');
-- Fails with: duplicate key value violates unique constraint "tag_pkey"
MERGE INTO tag AS t
USING incoming_tag AS s
ON t.name = s.name
WHEN NOT MATCHED THEN
INSERT (name) VALUES (s.name);The fix is to prepare the source so each key appears once:
MERGE INTO tag AS t
USING (SELECT DISTINCT name FROM incoming_tag) AS s
ON t.name = s.name
WHEN NOT MATCHED THEN
INSERT (name) VALUES (s.name);If the target has no unique constraint at all, there is no error. The duplicates are inserted, and you now have duplicate rows. Deduplicate the source whether or not a constraint would catch it.
NULL join keys
NULL = NULL is not true, so a source row with a null key never matches anything. It is "not matched" on every run, and the statement stops being idempotent. Filter such rows out of the source, or match them explicitly with IS NOT DISTINCT FROM in the ON condition. The second option can prevent PostgreSQL from using a hash or merge join, so measure it on large inputs.
Concurrent inserts
Another session can insert the same key after your statement has taken its snapshot and decided the row is missing. When your INSERT runs, the unique index reports a violation and the whole statement fails. MERGE does not retry the way INSERT ... ON CONFLICT does. Treat this as an expected error in busy systems: catch the unique_violation (SQLSTATE 23505) and retry the statement, or use ON CONFLICT DO NOTHING for pure insert-if-missing workloads. A later chapter covers the isolation details.
Referring to the target in the insert
-- Fails: the target row does not exist for an unmatched source row
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, t.quantity + s.delta)PostgreSQL rejects this at parse time. Compute the value from source columns only.
Choosing an insert-if-missing technique
| Technique | Needs a unique index | Handles concurrent inserts | Can also update or delete |
|---|---|---|---|
| `MERGE ... WHEN NOT MATCHED THEN INSERT` | No | No, can raise a unique violation | Yes |
| `INSERT ... ON CONFLICT DO NOTHING` | Yes | Yes | Update only, with `DO UPDATE` |
| `INSERT ... SELECT ... WHERE NOT EXISTS` | No | No, same race as `MERGE` | No |
Choose MERGE when the statement will also update or delete, or when the "does it exist" test is more than a unique key. Choose ON CONFLICT DO NOTHING when you only add missing rows into a table with a unique index and expect concurrent writers.
Checking the result
The command tag counts every row the statement affected, so MERGE 3 could mean three inserts or a mix of inserts, updates, and deletes. For an insert-only statement the count is the number of inserted rows. After the first run in this chapter, verify with a query:
SELECT product_id, name, quantity FROM inventory ORDER BY product_id;On PostgreSQL 17 and later you can add RETURNING merge_action(), t.* to see per-row results. That feature has its own chapter.
Exercise
A source table incoming_tag contains the names 'sql', 'sql' and 'postgres'. The target table tag has a primary key on name and is empty. You run MERGE INTO tag AS t USING incoming_tag AS s ON t.name = s.name WHEN NOT MATCHED THEN INSERT (name) VALUES (s.name);. What happens, why, and how do you fix it?
Show answer
The statement fails with a unique violation on the primary key. Both 'sql' rows are not matched, because the join looks only at the target as it was when the statement started, so both try to insert and the second collides with the first. The "cannot affect row a second time" error does not apply, since it concerns multiple source rows matching one existing target row. Fix it by deduplicating the source, for example USING (SELECT DISTINCT name FROM incoming_tag) AS s.
Exercise
You want to insert only products whose delta is positive and ignore all other unmatched source rows, without using a WHERE clause on the source. Write the WHEN clauses, and say what happens if you reverse their order.
Show answer
Write WHEN NOT MATCHED AND s.delta > 0 THEN INSERT (product_id, name, quantity) VALUES (s.product_id, s.name, s.delta) followed by WHEN NOT MATCHED THEN DO NOTHING. If you reverse the order, the unconditional DO NOTHING clause matches every unmatched row first, so nothing is ever inserted. PostgreSQL uses the first clause whose condition is true.
Exercise
Why does VALUES (s.product_id, s.name, t.quantity + s.delta) in a WHEN NOT MATCHED clause produce an error?
Show answer
An unmatched source row has no corresponding target row, so target columns have no value to refer to. In WHEN NOT MATCHED clauses, both the condition and the INSERT values may use only source columns, constants, and functions.