MERGE
the standard's way to sync one table into another. WHEN MATCHED, NOT MATCHED BY SOURCE, and RETURNING.
- address
- everything.writes.merge
- part
- part 5, changing data
- chapter
- chapter 5 of 10
- reading time
- 8 min
MERGE compares a source with a target table, row by row on a join condition, and says what to do with each kind of row: WHEN MATCHED (in both), WHEN NOT MATCHED (only in the source) and, since postgres 17, WHEN NOT MATCHED BY SOURCE (only in the target). each can UPDATE, DELETE, INSERT or DO NOTHING.
it's the standard's sync statement pg 15+. it is not a concurrency-safe upsert: that's still INSERT ... ON CONFLICT.
the picture
you know the nightly job that takes a supplier's file and makes your table match it? update what changed, add what's new, retire what's gone. people write that as three statements and a prayer. MERGE is the one statement for it.
think of checking a delivery against the shop shelf. each item on the delivery note and each item on the shelf gets paired up by sku. a pair (matched) might need a new price tag. a note item with no shelf spot (not matched) goes on the shelf. a shelf item that's not on the note (not matched by source) gets a "discontinued" sticker.
| skutext | nametext | pricenumeric | discontinuedbool |
|---|---|---|---|
| BOO-0003 | the art of sql | 32.00 | f |
| BOO-0028 | bamboo cookbook | 16.90 | f |
| BOO-0053 | mini notebook | 153.60 | f |
| BOO-0054 | compact novel | 73.76 | f |
| BOO-0060 | travel field guide | 67.89 | f |
| BOO-0097 | deluxe notebook | 114.68 | f |
| BOO-0114 | mini atlas | 78.86 | f |
| BOO-0120 | large cookbook | 16.60 | f |
| BOO-0122 | spare atlas | 174.68 | f |
| BOO-0137 | cotton atlas | 51.95 | f |
| BOO-0142 | deluxe cookbook | 128.41 | f |
| BOO-0177 | cotton cookbook | 196.45 | f |
shop's books before the merge.
every block here runs on a fresh copy of shop, so nothing you do sticks. the supplier's list is a table of its own:
CREATE TABLE feed (sku text PRIMARY KEY, name text NOT NULL, price numeric(10,2) NOT NULL);
INSERT INTO feed VALUES
('BOO-0003', 'the art of sql', 32.00),
('BOO-0028', 'bamboo cookbook', 17.50),
('BOO-0053', 'mini notebook', 153.60),
('BOO-0054', 'compact novel', 69.00),
('BOO-0060', 'travel field guide', 67.89),
('BOO-0097', 'deluxe notebook', 114.68),
('BOO-0120', 'large cookbook', 16.60),
('BOO-0142', 'deluxe cookbook', 128.41),
('BOO-0201', 'the sql cookbook', 24.00),
('BOO-0202', 'sql antipatterns', 38.00);the clauses
the whole statement, once:
WITH m AS (
MERGE INTO products AS p
USING feed AS f ON p.sku = f.sku
WHEN MATCHED AND p.price <> f.price THEN
UPDATE SET price = f.price
WHEN NOT MATCHED THEN
INSERT (sku, name, category, price) VALUES (f.sku, f.name, 'books', f.price)
WHEN NOT MATCHED BY SOURCE AND p.category = 'books' THEN
UPDATE SET discontinued = true
RETURNING merge_action() AS action, p.sku, old.price AS old_price, new.price AS new_price
)
SELECT * FROM m ORDER BY action, sku;| actiontext | skutext | old_pricenumeric | new_pricenumeric |
|---|---|---|---|
| INSERT | BOO-0201 | null | 24.00 |
| INSERT | BOO-0202 | null | 38.00 |
| UPDATE | BOO-0028 | 16.90 | 17.50 |
| UPDATE | BOO-0054 | 73.76 | 69.00 |
| UPDATE | BOO-0114 | 78.86 | 78.86 |
| UPDATE | BOO-0122 | 174.68 | 174.68 |
| UPDATE | BOO-0137 | 51.95 | 51.95 |
| UPDATE | BOO-0177 | 196.45 | 196.45 |
read it top to bottom. MERGE INTO names the target, USING the source (a table, a query, a VALUES list), ON how rows pair up. then the WHEN clauses, and the action for each:
| clause | the row is | actions allowed |
|---|---|---|
WHEN MATCHED | in both: the ON condition found a pair | UPDATE, DELETE, DO NOTHING |
WHEN NOT MATCHED [BY TARGET] | only in the source | INSERT, DO NOTHING |
WHEN NOT MATCHED BY SOURCE pg 17+ | only in the target | UPDATE, DELETE, DO NOTHING |
each clause can carry an AND condition, and the clauses are tried in the order you wrote them: the first one whose condition holds wins, and no row gets more than one action. six of the matched books had the same price, so their clause's AND p.price <> f.price was false and, with no other MATCHED clause to try, they were left alone. that's how 10 feed rows and 12 books come out as 8 actions: 2 updates, 2 inserts, 4 discontinued.
RETURNING pg 17+ with merge_action() says which action each row got, and old and new pg 18+ work like they do everywhere else. MERGE inside WITH, as above, is how you sort what it returns.
- 1MERGE INTO products AS p
- 2USING feed AS f ON p.sku = f.sku
- 3WHEN MATCHED AND p.price <> f.price THEN
- 4 UPDATE SET price = f.price
- 5RETURNING merge_action() AS action, p.sku, old.price AS old_price, new.price AS new_price, p.discontinued;
| actiontext | skutext | old_pricenumeric | new_pricenumeric | discontinuedbool |
|---|---|---|---|---|
| UPDATE | BOO-0028 | 16.90 | 17.50 | f |
| UPDATE | BOO-0054 | 73.76 | 69.00 | f |
only WHEN MATCHED: the two books whose price changed are updated. everything else is left alone.
AND p.category = 'books' from the BY SOURCE clause. a feed of books doesn't mention the 188 products that aren't books either, so they get discontinued too.order matters
because the first true clause wins, an early, narrower clause shadows a later one. here: never lower a price (do nothing), otherwise take the feed's price. (this runs on a fresh shop with the same feed, not after the merge above.)
MERGE INTO products AS p
USING feed AS f ON p.sku = f.sku
WHEN MATCHED AND f.price < p.price THEN
DO NOTHING
WHEN MATCHED AND f.price > p.price THEN
UPDATE SET price = f.price;MERGE 1: bamboo cookbook's price went up from 16.90 to 17.50, compact novel's would have gone down and was skipped, and DO NOTHING doesn't count. put an unconditional clause first and postgres catches the dead code for you:
MERGE INTO products AS p
USING feed AS f ON p.sku = f.sku
WHEN MATCHED THEN DO NOTHING
WHEN MATCHED AND f.price > p.price THEN UPDATE SET price = f.price;-- the source has two rows for the same book
MERGE INTO products AS p
USING (VALUES ('BOO-0003', 29.00), ('BOO-0003', 35.00)) AS f (sku, price)
ON p.sku = f.sku
WHEN MATCHED THEN UPDATE SET price = f.price;MERGE INTO products AS p
USING (VALUES ('BOO-0003', 29.00), ('BOO-0003', 35.00)) AS f (sku, price)
ON p.sku = f.sku
WHEN MATCHED THEN UPDATE SET price = f.price;MERGE is not an upsert
a MERGE with a MATCHED UPDATE and a NOT MATCHED INSERT looks exactly like an upsert. alone in the database, it behaves like one. with someone else inserting the same key at the same moment, it doesn't:
| sku | qty |
|---|---|
| TEA-01 | 10 |
T1 opens a transaction.
MERGE joins first and decides each row's action from what it saw. T2 saw no TEA-02 (T1's wasn't committed), so it chose INSERT, and when the unique index made it wait and T1 committed, the INSERT failed. the manual says so directly: MERGE doesn't go back and re-evaluate its MATCHED clauses after a concurrent insert, and it suggests INSERT ... ON CONFLICT when that matters. ON CONFLICT is built around the unique index, so it can switch to the update after the wait. (INSERT ... ON CONFLICT has that race step by step.)
so: MERGE for batch syncs, where one job owns the table for a while, or where a retry is fine. ON CONFLICT for upserts that many sessions run at once.
one level deeperwhat's standard and what's postgres
MERGE is in the SQL standard (since SQL:2003), and postgres supports it since 15. the manual's compatibility notes list what postgres adds on top: BY SOURCE and BY TARGET, the DO NOTHING action, RETURNING, and a WITH clause in front. sql server has the same WHEN NOT MATCHED BY SOURCE clause. the release notes for 17 list both BY SOURCE and RETURNING with merge_action().
keylines
- MERGE pairs source and target rows with ON, then runs the first WHEN clause that's true for each pair.
- MATCHED: in both. NOT MATCHED: only in the source. NOT MATCHED BY SOURCE (pg 17): only in the target.
- BY SOURCE judges the whole target table: limit it with an AND.
- a target row can change only once: duplicate source rows are an error, not a coin toss.
- for concurrent upserts, ON CONFLICT is the safe one. MERGE can fail with 23505.