skip to content

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.

before anything runs
products, the books, after this step
products, the books after: before
skutextnametextpricenumericdiscontinuedbool
BOO-0003the art of sql32.00f
BOO-0028bamboo cookbook16.90f
BOO-0053mini notebook153.60f
BOO-0054compact novel73.76f
BOO-0060travel field guide67.89f
BOO-0097deluxe notebook114.68f
BOO-0114mini atlas78.86f
BOO-0120large cookbook16.60f
BOO-0122spare atlas174.68f
BOO-0137cotton atlas51.95f
BOO-0142deluxe cookbook128.41f
BOO-0177cotton cookbook196.45f
(12 rows)
new rowchanged

shop's books before the merge.

step 1/2
real output, postgres 18.6 (PGlite 0.5.12) · merge
shop's 12 books before and after one MERGE with a supplier's list of 10. two prices change (hot), two new books arrive (live), four books missing from the list are marked discontinued.

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:

feed.sqldb=shop · session feed
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);
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 10

the clauses

the whole statement, once:

sqldb=shop · session feed
continues session feed (1 earlier block run first)
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;
output, from postgres 18.6
SELECT 8
actiontextskutextold_pricenumericnew_pricenumeric
INSERTBOO-0201null24.00
INSERTBOO-0202null38.00
UPDATEBOO-002816.9017.50
UPDATEBOO-005473.7669.00
UPDATEBOO-011478.8678.86
UPDATEBOO-0122174.68174.68
UPDATEBOO-013751.9551.95
UPDATEBOO-0177196.45196.45
(8 rows)

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:

clausethe row isactions allowed
WHEN MATCHEDin both: the ON condition found a pairUPDATE, DELETE, DO NOTHING
WHEN NOT MATCHED [BY TARGET]only in the sourceINSERT, DO NOTHING
WHEN NOT MATCHED BY SOURCE pg 17+only in the targetUPDATE, 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.

clauses =
merge.sql
  1. 1MERGE INTO products AS p
  2. 2USING feed AS f ON p.sku = f.sku
  3. 3WHEN MATCHED AND p.price <> f.price THEN
  4. 4 UPDATE SET price = f.price
  5. 5RETURNING merge_action() AS action, p.sku, old.price AS old_price, new.price AS new_price, p.discontinued;
the result for MATCHED
actiontextskutextold_pricenumericnew_pricenumericdiscontinuedbool
UPDATEBOO-002816.9017.50f
UPDATEBOO-005473.7669.00f
(2 rows)

only WHEN MATCHED: the two books whose price changed are updated. everything else is left alone.

real output, postgres 18.6 (PGlite 0.5.12) · merge
add the clauses one at a time and watch what MERGE returns: updates and inserts. the last option drops 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.)

sqldb=shop · session order
continues session order (1 earlier block run first)
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;
output, from postgres 18.6
MERGE 1

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:

sqldb=shop · session feed
continues session feed (2 earlier blocks run first)
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;
output, from postgres 18.6
ERROR 42601: unreachable WHEN clause specified after unconditional WHEN clause
predict the output
sql
-- 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;
sqldb=shop
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;
output, from postgres 18.6
ERROR 21000: MERGE command cannot affect row a second time
HINT: Ensure that not more than one source row matches any one target row.

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:

statement =
T1
·
T2
·
1
BEGIN
committed in the database
skuqty
TEA-0110

T1 opens a transaction.

step 1/6
real output, a postgres 18.6 server · merge-race
two real sessions on a postgres 18.6 server deliver the same new sku. switch between MERGE and INSERT ... ON CONFLICT and step through. both make T2 wait for T1. only one of them has a plan for what to do after the wait.

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.