Sub topic 1
SQL MERGE in PostgreSQL: What MERGE Does and When It Runs
Prerequisites
This chapter assumes you know basic SQL SELECT, INSERT, UPDATE, and DELETE. You should understand joins, join conditions, primary keys, and unique constraints. MERGE requires PostgreSQL 15 or later.
What MERGE does and when it runs
MERGE compares rows in a target table with rows from a source. For each source row, it either updates the matching target row or inserts a new one. Without MERGE, you would write separate UPDATE and INSERT statements and check for matches yourself.
A MERGE statement runs as one command. All of its changes succeed or fail together, so wrap it in a transaction if you need that guarantee across several statements.
Choosing the target table and the source rows
The target is the table you change. The source is a table or query that supplies the new values. A staging table is a common choice:
MERGE INTO customers AS t
USING staging_customers AS s
ON t.customer_id = s.customer_id
WHEN MATCHED THEN
UPDATE SET email = s.email, updated_at = now()
WHEN NOT MATCHED THEN
INSERT (customer_id, email, updated_at)
VALUES (s.customer_id, s.email, now());The aliases t and s name the target and source. You use them to tell the two tables apart.
Matching rows with the ON condition
The ON clause decides which source row pairs with which target row. A pair that satisfies the condition is a match. A source row with no partner in the target is not matched.
| Situation | Branch that runs |
|---|---|
| Source row matches a target row | WHEN MATCHED |
| Source row has no matching target row | WHEN NOT MATCHED |
Match on a primary key or a unique column. If one source row matches several target rows, PostgreSQL raises an error.
Updating matched rows
The WHEN MATCHED THEN UPDATE branch changes the target row. Columns on the left side of SET belong to the target. Columns on the right can read from the source alias s.
Exercise
In the example, which table is the target, and which branch runs for a staging row whose customer_id is not in customers?
Show answer
The target is customers. The WHEN NOT MATCHED branch runs, which inserts a new row into customers.