Sub topic 1
Why MERGE exists
Applications often receive a batch of changes and must bring a table in line with it. Some rows in the batch are new. Some describe rows that already exist. Sometimes a row means "remove this". This chapter explains why that job is awkward with plain INSERT, UPDATE and DELETE, and how the MERGE statement handles it in one statement. It also sets up the tables the later chapters use.
Prerequisites
This chapter assumes you already know:
- Basic
SELECT,INSERT,UPDATEandDELETE. - How joins and join conditions work.
- What primary keys and unique constraints are.
- Subqueries and table aliases.
- What a transaction is, and that
BEGINandCOMMITgroup statements together.
You also need a PostgreSQL 15 or later server to run MERGE. Check your version with:
SHOW server_version;The later chapters cover the features added in PostgreSQL 17. This chapter does not need them.
The synchronize-or-upsert problem
Imagine a warehouse database. The inventory table holds one row per product. Throughout the day, other systems write stock changes into a staging table called inventory_updates. Each staged row says "product X changed by this amount". Periodically you must apply the staged changes to inventory.
Each staged row falls into one of two cases:
- The product already exists in
inventory. Update its quantity. - The product does not exist yet. Insert a new row.
Developers call this an upsert, a blend of "update" and "insert". A broader version is synchronization. In it, the target table must mirror a source, which may also require deleting rows. Typical examples are:
- Loading a nightly file of customer records into a customers table.
- Applying change-data-capture events to a reporting table.
- Refreshing a lookup table from an external feed.
- Keeping a summary table in step with a detail table.
The shared pattern is a target (the table you change) and a source (the rows describing the change). The two are compared on a key, and the outcome for each row depends on whether a match exists.
Setting up the example tables
The chapters in this tutorial use the same two tables. Run this once.
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);inventory has products 1 and 2. The staged updates add 25 nuts (product 2, which exists) and 40 washers (product 3, which does not). The correct result after synchronizing is:
| product_id | name | quantity |
|---|---|---|
| 1 | bolt | 100 |
| 2 | nut | 75 |
| 3 | washer | 40 |
Product 1 has no staged change, so it stays as it is.
The old way: two statements
Before PostgreSQL 15, the usual answer was two statements inside one transaction. The first updates the rows that match. The second inserts the rows that do not.
BEGIN;
UPDATE inventory AS t
SET quantity = t.quantity + s.delta,
updated_at = now()
FROM inventory_updates AS s
WHERE t.product_id = s.product_id;
INSERT INTO inventory (product_id, name, quantity)
SELECT s.product_id, s.name, s.delta
FROM inventory_updates AS s
WHERE NOT EXISTS (
SELECT 1 FROM inventory AS t
WHERE t.product_id = s.product_id
);
COMMIT;This works, but it has several weaknesses.
- The order matters. The
UPDATEruns first. If you ran theINSERTfirst, the new washer row would then be matched by theUPDATEand its quantity would be added to itself, giving 80 instead of 40. - The join logic is written twice. The match condition appears in the
WHEREof the update and again in theNOT EXISTSof the insert. If you change one and forget the other, rows are skipped or duplicated. - The work is done twice. PostgreSQL scans and joins the source against the target two times.
- Duplicate source rows behave badly. If
inventory_updatescontains two rows for product 2,UPDATE ... FROMapplies only one of them, and PostgreSQL does not say which. If it contains two rows for new product 3, theINSERTfails with a primary key violation. - It is not safe on its own under concurrency. Another session can insert product 3 between your
UPDATEand yourINSERT. YourINSERTthen fails with a unique violation. A transaction at the default isolation level does not prevent this. - Deletes need a third statement. Each extra action adds another pass and another place for the logic to drift.
Other workarounds
PostgreSQL offered other tools for upserts before version 15:
INSERT ... ON CONFLICT, added in PostgreSQL 9.5. It inserts, and on a unique-key collision it updates or skips instead. It is fast and handles concurrent inserts well. It can only insert or update, and it needs a unique index on the conflict columns. A later chapter compares it withMERGEin detail.- A writable common table expression (CTE). A CTE can run the
UPDATE ... RETURNINGand a followingINSERTthat excludes the returned keys. This keeps everything in one statement. It is easy to get subtly wrong and has the same concurrency gap as the two-statement version. - A PL/pgSQL loop. A function can try an
UPDATE, and if no row was found, try anINSERTand retry on a unique violation. It is correct but verbose, slow for large batches because it works row by row, and has to be written for each table.
None of these expresses the original idea directly: compare two sets of rows and decide per row what to do.
What MERGE does
MERGE is the SQL standard's answer. It was added in the SQL:2003 standard and appears in many databases. PostgreSQL added it in version 15. A MERGE statement names a target table, a source, and a join condition. It then lists what to do for each row depending on whether the join found a match.
Here is the upsert from this chapter as a single statement:
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);Read it from top to bottom:
MERGE INTO inventory AS tnames the target, the table that will change.USING inventory_updates AS snames the source, which can be a table, a view or a subquery.ON t.product_id = s.product_idis the join condition. It decides which target row each source row matches.WHEN MATCHED THEN UPDATE ...runs for source rows that found a target row.WHEN NOT MATCHED THEN INSERT ...runs for source rows that found no target row.
PostgreSQL joins the source to the target once and applies the right action to each source row. The match logic is written once, so it cannot drift apart. The whole statement runs under a single snapshot and either succeeds or rolls back as a unit.
Run it and check the result
If you ran the setup script above, run the MERGE and then look at the table:
SELECT product_id, name, quantity FROM inventory ORDER BY product_id;You should see:
product_id | name | quantity
------------+--------+----------
1 | bolt | 100
2 | nut | 75
3 | washer | 40
(3 rows)psql reports the result of the MERGE itself as a command tag, MERGE 2. The number counts every row the statement inserted, updated or deleted. Here one row was updated and one was inserted. Product 1 had no source row, so it was left alone.
Version history
| PostgreSQL version | What changed for MERGE |
|---|---|
| 15 | `MERGE` introduced with `WHEN MATCHED` and `WHEN NOT MATCHED`. |
| 17 | Added `WHEN NOT MATCHED BY SOURCE`, `RETURNING` with `merge_action()`, and support for updatable views as targets. |
If you run MERGE on PostgreSQL 14 or earlier, you get a syntax error such as syntax error at or near "MERGE". The fix is to upgrade, or to use the older patterns described above.
Where MERGE fits
MERGE is the right fit when the work is a set-based comparison of a source against a target. It is a good choice when:
- You apply batches of changes from a staging table or a query.
- You need more than insert-or-update, for example deleting rows that reach zero.
- You want to choose different actions for different rows based on conditions.
- You want the logic to be portable to other databases that support standard
MERGE.
It is not a magic fix for every upsert. Keep these limits in mind as you go through the rest of the tutorial:
- A target row may match at most one source row. If two source rows match the same target row, PostgreSQL raises a cardinality error rather than guess. A later chapter shows how to prepare the source to avoid this.
- Concurrent writers can still collide.
MERGEdoes not take a lock that prevents another session from inserting the same key. The insert can then fail with a unique violation.INSERT ... ON CONFLICTis designed to handle that case, and a later chapter explains when each is better. - Joins need indexes. Matching a large source against a large target without an index on the join columns can be slow.
Common mistakes at this stage
- Forgetting the alias scope. In the
UPDATE SETlist, name the target column without an alias, as inSET quantity = .... WritingSET t.quantity = ...is a syntax error. You can use aliases on the right side of the assignment. - Using a pre-15 server. The statement fails to parse. Check
SHOW server_version;first. - Expecting a missing source row to delete the target row. Plain
MERGEonly acts on rows that exist in the source. Product 1 was untouched. Deleting target rows that are absent from the source needsWHEN NOT MATCHED BY SOURCE, which requires PostgreSQL 17 and is covered later. - Re-running the setup.
CREATE TABLE inventoryfails if the table already exists. RunDROP TABLE inventory, inventory_updates;first if you want a clean start.
Summary
The synchronize-or-upsert problem asks you to compare a source set of rows with a target table and insert, update or delete based on whether each row matches. The older two-statement approach works but repeats the match logic, scans the data twice and leaves gaps around duplicates and concurrency. MERGE, available since PostgreSQL 15, expresses the whole decision in one statement with a target, a USING source and an ON condition. The next chapter takes that statement apart clause by clause.
Exercise
A colleague runs the two-statement pattern but puts the INSERT (with its NOT EXISTS check) before the UPDATE. Using the example data (inventory has products 1 and 2; updates are product 2 with delta 25 and product 3 with delta 40), what quantity does product 3 end up with, and why?
Show answer
Product 3 ends up with 80. The INSERT adds product 3 with quantity 40. The UPDATE that follows then matches product 3 in inventory because the row now exists, so it adds the delta of 40 again. Running the UPDATE first avoids this. A single MERGE avoids it too, because it decides each source row's action from one join before changing anything.
Exercise
Name two things plain INSERT ... ON CONFLICT cannot do that MERGE can, and name the PostgreSQL version that introduced MERGE.
Show answer
ON CONFLICT can only insert or update (or skip). It cannot delete rows, and it cannot choose between several different actions based on conditions on the matched row, such as deleting when a quantity reaches zero. MERGE can do both. MERGE was introduced in PostgreSQL 15.
Exercise
You run the MERGE from this chapter on a PostgreSQL 14 server and see "syntax error at or near MERGE". What are two ways to fix the problem?
Show answer
Upgrade the server to PostgreSQL 15 or later, where MERGE is supported. Or rewrite the logic with the older patterns: an UPDATE ... FROM followed by an INSERT ... WHERE NOT EXISTS in one transaction, or INSERT ... ON CONFLICT DO UPDATE if a unique index exists on the key.