Sub topic 2
Anatomy of a MERGE statement
This chapter takes a MERGE statement apart clause by clause. It explains what each part does, how PostgreSQL evaluates it, and which mistakes show up first. Later chapters cover conditions, duplicate-source errors, concurrency, and the PostgreSQL 17 additions in more detail.
Prerequisites and setup
This chapter assumes you can:
- Write basic SELECT, INSERT, UPDATE, and DELETE statements.
- Read a join and its ON condition.
- Use primary keys and aliases.
- Run a statement inside a transaction.
MERGE was added in PostgreSQL 15. Everything in this chapter runs on version 15 or later. Features that need version 17 are marked as such.
The examples use two tables. inventory is the target, the table you want to change. inventory_updates is the source, a set of changes to apply.
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);Product 2 exists in both tables. Product 3 exists only in the source. Product 1 exists only in the target. These three cases are the ones MERGE is designed to tell apart.
The basic shape
A MERGE statement has three required parts and one or more action clauses:
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 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);Run it and PostgreSQL replies with a command tag:
MERGE 2The number is the total count of rows inserted, updated, or deleted. Here one row was updated (product 2) and one was inserted (product 3). The tag does not say which was which. The RETURNING clause in PostgreSQL 17 can do that, and a later chapter covers it.
After the statement, inventory holds bolt 100, nut 75, and washer 40. Product 1 was not touched, because no source row refers to it.
The target: MERGE INTO
MERGE INTO inventory AS t names the table that will be modified. The alias is optional but strongly recommended. Most MERGE statements refer to both the target and the source in the same expression, and short aliases like t and s keep that readable.
The target must be something PostgreSQL can write to row by row:
- An ordinary table or a partitioned table works.
- An automatically updatable view works from PostgreSQL 17.
- A materialized view, a foreign table, or a table that has rules defined on it is not supported as a target.
You need the privilege for each action you use. UPDATE needs the UPDATE privilege on the target, INSERT needs INSERT, and DELETE needs DELETE. You also need SELECT on the target if any expression reads its columns. The ON condition does, so in practice you almost always need SELECT. Row-level security and triggers apply as they would for the equivalent plain statements.
The source: USING
USING supplies the rows to compare against the target. The source can be any of these:
- A table or view.
- A subquery.
- A VALUES list.
- A function that returns rows.
- A join of several of these.
A VALUES list is convenient when the changes come from application code and there is no staging table:
MERGE INTO inventory AS t
USING (VALUES (2, 'nut', 25), (3, 'washer', 40)) AS s(product_id, name, delta)
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);Because VALUES has no column names of its own, the alias list s(product_id, name, delta) supplies them.
Subqueries are how you prepare the source. You can filter, join, aggregate, or deduplicate before MERGE sees a row. This matters because MERGE raises an error if two source rows match the same target row. The chapter on the duplicate-source error covers that rule. For now, remember that the subquery is the place to fix such problems.
The join condition: ON
ON t.product_id = s.product_id decides which source rows match which target rows. It works like a join condition, and MERGE conceptually joins the source to the target. Each source row ends up in one of two groups:
- Matched: at least one target row satisfies the ON condition for that source row.
- Not matched: no target row satisfies it.
The ON condition does not have to be a primary-key comparison. Any boolean expression works, including multiple columns joined with AND. But the choice has consequences:
- If the condition matches a target row against more than one source row, MERGE fails at run time.
- If it matches nothing because of a typo or a NULL, every source row is treated as not matched. A MERGE with a WHEN NOT MATCHED INSERT clause then inserts everything, which can create duplicates if the table has no unique constraint.
- NULL never equals NULL in a comparison. A source row with a NULL
product_idis never matched, and it goes down the not-matched path.
A common mistake is to put a filter in ON, hoping it restricts which rows are acted on. Consider a source row that fails the filter. It is no longer matched, so it falls into the not-matched group and may be inserted. Keep ON for the relationship between the two tables. Put row-filtering logic in an AND condition on the WHEN clause, which the next chapter covers.
The action clauses: WHEN
After ON come one or more WHEN clauses. Each has a match kind, an optional condition, and an action.
| Clause | Applies to | Allowed actions |
|---|---|---|
| `WHEN MATCHED` | Source rows that matched a target row | `UPDATE`, `DELETE`, `DO NOTHING` |
| `WHEN NOT MATCHED` | Source rows with no target row | `INSERT`, `DO NOTHING` |
| `WHEN NOT MATCHED BY SOURCE` (PostgreSQL 17) | Target rows with no source row | `UPDATE`, `DELETE`, `DO NOTHING` |
WHEN NOT MATCHED is shorthand for WHEN NOT MATCHED BY TARGET. In PostgreSQL 17 you can write either form. The BY SOURCE form is the one that looks at target rows the source did not mention. It gets its own chapter.
For each row, PostgreSQL tests the WHEN clauses of the right kind in the order you wrote them. The first one whose condition is true runs, and the rest are skipped for that row. If no clause applies, the row is left alone. A MERGE with only a WHEN MATCHED clause never inserts. A MERGE with only a WHEN NOT MATCHED clause never updates.
The diagram shows the decision made for each source row.
Writing the actions
The syntax inside each action follows the plain statements, with a few differences.
UPDATE
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()There is no table name after UPDATE, because the target is already known. The columns on the left of = must not be qualified. Writing SET t.quantity = ... is a syntax error. On the right side you can reference columns from both the target and the source. Qualify them with the aliases, because quantity alone would be ambiguous if both sides had such a column.
The UPDATE has no WHERE clause. Row selection is done by the ON condition and the optional condition on the WHEN clause.
DELETE
WHEN MATCHED THEN DELETEDELETE takes no arguments. It removes the matched target row.
INSERT
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)The column list is optional, but writing it makes the statement safe against later table changes. The values can reference only the source. There is no target row yet, so t.quantity here is an error. Columns you leave out take their defaults, which is how updated_at gets now() above. You can also write INSERT DEFAULT VALUES.
DO NOTHING
DO NOTHING explicitly skips the row. It is useful when a conditional clause should absorb some rows before a later clause sees them. Because the first true clause wins, this lets you carve out exceptions.
Source rows that match nothing and want nothing
Not every source row has to produce a change. In the first example, if you removed the NOT MATCHED clause, product 3 would be silently ignored. MERGE does not warn you. If a MERGE reports fewer rows than you expected, check which clauses you wrote and what their conditions are.
Triggers, transactions, and atomicity
A MERGE is a single statement, so it is atomic. If any row causes an error, such as a constraint violation or a failed cast, the whole statement is rolled back and no row is changed. Inside a larger transaction, it behaves like any other statement.
Triggers fire as they would for the equivalent plain statements. Row-level BEFORE and AFTER triggers fire for each inserted, updated, or deleted row. Statement-level triggers for INSERT, UPDATE, and DELETE fire only if MERGE has at least one action clause of that kind, whether or not any row was affected by it.
A quick way to check your understanding of a statement
When you read or write a MERGE, ask four questions in order:
- What is the target, and which privileges does the role have on it?
- What does one row of the source look like? Is it unique per join key?
- What does the ON condition say about when two rows match?
- For matched and unmatched rows, which first clause applies, and what does it do?
If you can answer all four, you can predict the result and the row count in the command tag. The inventory example gives these answers:
- The target is
inventory. - The source has one row per
product_id. - Rows match on
product_id. - Matched rows add the delta, and unmatched rows are inserted.
The expected tag is MERGE 2.
Summary of rules from this chapter
MERGE INTO target USING source ON conditionis the skeleton, followed by one or more WHEN clauses.- ON splits source rows into matched and not matched. NULL keys never match.
- Clauses are tested in order for each row, and the first with a true condition runs.
- UPDATE columns are unqualified. INSERT values can reference only the source.
- The statement is atomic and returns a count of changed rows, not a breakdown by action.
Exercise
A colleague writes a MERGE whose ON condition is t.product_id = s.product_id AND s.delta > 0, with a WHEN NOT MATCHED THEN INSERT clause. The source contains a row (2, 'nut', -10), and product 2 already exists in the target. What happens to that source row, and how should the statement be changed?
Show answer
The row fails s.delta > 0, so it does not match the existing product 2 row. It is classified as not matched, and the INSERT clause tries to insert a second row for product 2. With a primary key on product_id this raises a unique violation, and the whole statement is rolled back. Remove AND s.delta > 0 from ON, and express the intent in WHEN clause conditions instead, for example WHEN MATCHED AND s.delta > 0 THEN UPDATE ... and WHEN NOT MATCHED AND s.delta > 0 THEN INSERT ....
Exercise
Why does the following statement fail, and what is the fix? MERGE INTO inventory AS t USING inventoryupdates AS s ON t.productid = s.product_id WHEN MATCHED THEN UPDATE SET t.quantity = t.quantity + s.delta;
Show answer
The column on the left side of SET is qualified with the alias t, which is a syntax error in MERGE. Write SET quantity = t.quantity + s.delta. The expression on the right can keep the qualified names.
Exercise
What does the command tag MERGE 3 tell you, and what does it not tell you?
Show answer
It says that three rows in total were inserted, updated, or deleted by the statement. It does not say how many of each kind. To see the action per row, use RETURNING with merge_action() on PostgreSQL 17 or later.