MERGE INTO and upserts
Most data changes are not pure inserts: customers change address, orders get cancelled, a feed sends corrections. MERGE applies inserts, updates and deletes to a table in one atomic step. This lesson walks through its clauses one by one, and the duplicate-row error everyone meets.
Step 3 · Data lake & lakehouse · Silver · Changing data, lesson 1 of 3
On this page
Show code in
Every code block on the page follows this.
Read first: The Delta transaction log · join (skip if you know them)
In plain words first
Updating a class register from a list of changes: for each name on the list, if the student is already in the register, update their details; if not, add them; if the list says they left, cross them out. You go through the list once and apply each change.
MERGE does exactly that, for a whole table, in one commitcommit: One atomic change to a table: a new version that lists which files were added and removed. Learn more →.
What it does
MERGE is the standard way to apply changes (upserts, CDC feeds, corrections) to a lakehouse table. One statement, one atomic commit, no window in which readers see half the changes.
from delta.tables import DeltaTable (DeltaTable.forName(spark, "customers").alias("t") .merge(updates.alias("s"), "t.customer_id = s.customer_id") .whenMatchedDelete(condition="s.op = 'DELETE'") .whenMatchedUpdate(set={"email": "s.email", "tier": "s.tier", "updated_at": "s.ts"}) .whenNotMatchedInsert(condition="s.op != 'DELETE'", values={ "customer_id": "s.customer_id", "email": "s.email", "tier": "s.tier", "updated_at": "s.ts", }) .whenNotMatchedBySourceDelete(condition="t.tier = 'trial'") .execute())
MERGE INTO customers t USING updates s ON t.customer_id = s.customer_id WHEN MATCHED AND s.op = 'DELETE' THEN DELETE WHEN MATCHED THEN UPDATE SET t.email = s.email, t.tier = s.tier, t.updated_at = s.ts WHEN NOT MATCHED AND s.op != 'DELETE' THEN INSERT (customer_id, email, tier, updated_at) VALUES (s.customer_id, s.email, s.tier, s.ts) WHEN NOT MATCHED BY SOURCE AND t.tier = 'trial' THEN DELETE
The clauses
| Clause | Applies to | Can |
|---|---|---|
WHEN MATCHED [AND cond] | Target rows with a matching source row | UPDATE or DELETE |
WHEN NOT MATCHED [AND cond] | Source rows with no target match | INSERT |
WHEN NOT MATCHED BY SOURCE [AND cond] | Target rows with no source match | UPDATE or DELETE (Delta 2.3+, Iceberg with recent Spark) |
- Clauses of the same kind are checked in order; the first whose condition holds is applied to a row.
UPDATE SET *andINSERT *copy all columns by name.- Without a NOT MATCHED BY SOURCE clause, target rows absent from the source are untouched. With an unconditional one, MERGE becomes a full sync and deletes everything not in the source: be careful.
How MERGE executes
Step 1 · find touched files
Step 2 · rewrite
Step 3 · commit
Cost · what dominates
The duplicate source error
If two source rows match the same target row, MERGE cannot know which update to apply, so it fails (Delta reports that multiple source rows matched the same target row). The fix is to make the source unique per key before merging, usually keeping the latest change:
spark.sql(""" WITH latest AS ( SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ts DESC) AS rn FROM updates) WHERE rn = 1) MERGE INTO customers t USING latest s ON t.customer_id = s.customer_id WHEN MATCHED THEN UPDATE SET * WHEN NOT MATCHED THEN INSERT * """)
WITH latest AS ( SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ts DESC) AS rn FROM updates) WHERE rn = 1) MERGE INTO customers t USING latest s ON t.customer_id = s.customer_id WHEN MATCHED THEN UPDATE SET * WHEN NOT MATCHED THEN INSERT *
Making MERGE faster
- Put selective predicates in the ON condition, for example
AND t.event_date >= '2025-03-01', so file skipping can prune the target. - Cluster the target by the merge key (Z-orderZ-order: Sorting data by several columns at once, so queries filtering on any of them can skip more files. Learn more → or liquid clustering) so matches concentrate in few files.
- Enable deletion vectors (Delta) or merge-on-readmerge-on-read: Applying an update by recording the change and combining it when reading: fast writes, extra work for readers. Learn more → (Iceberg) for update-heavy tables.
- Keep the source small: merge only changed rows, not a full snapshotsnapshot: A complete, consistent version of a table at one moment. Readers always see one snapshot, never a half-finished write. Learn more →.
- Broadcastbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more → a small source; check the join strategy in the plan.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session with Delta Lake, with spark already created: each builds its own data.
Goal: Upsert a batch of changes with one MERGE: update, insert, delete, and remove rows missing from the batch.
import os from delta.tables import DeltaTable path = os.path.abspath("lab/merge/customers") (spark.createDataFrame( [(1, "ana@x.in", "gold"), (2, "bo@x.in", "trial"), (3, "cy@x.in", "silver")], ["customer_id", "email", "tier"]) .write.format("delta").mode("overwrite").save(path)) changes = spark.createDataFrame( [(1, "ana@new.in", "gold", "U"), (3, None, None, "D"), (4, "di@x.in", "silver", "I")], ["customer_id", "email", "tier", "op"]) (DeltaTable.forPath(spark, path).alias("t") .merge(changes.alias("s"), "t.customer_id = s.customer_id") .whenMatchedDelete(condition="s.op = 'D'") .whenMatchedUpdate(set={"email": "s.email", "tier": "s.tier"}) .whenNotMatchedInsert(values={"customer_id": "s.customer_id", "email": "s.email", "tier": "s.tier"}) # missing from the batch .whenNotMatchedBySourceDelete(condition="t.tier = 'trial'") .execute()) spark.read.format("delta").load(path).orderBy("customer_id").show() dupes = spark.createDataFrame([(1, "a1@x.in"), (1, "a2@x.in")], ["customer_id", "email"]) try: (DeltaTable.forPath(spark, path).alias("t") .merge(dupes.alias("s"), "t.customer_id = s.customer_id") .whenMatchedUpdate(set={"email": "s.email"}).execute()) except Exception as e: print("duplicate source rows:", str(e).split("]")[0] + "]")
Output from a real run
+-----------+----------+------+ |customer_id| email| tier| +-----------+----------+------+ | 1|ana@new.in| gold| | 4| di@x.in|silver| +-----------+----------+------+ duplicate source rows: [DELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGE]
What to notice:
- Customer 1 was updated (new email), customer 3 deleted (
op = 'D'), customer 4 inserted. - Customer 2 was a trial customer missing from the batch, so
whenNotMatchedBySourceDeleteremoved it. - The second MERGE failed: two source rows match customer 1, and Delta will not guess which wins. Deduplicate the source first.
Common mistakes
- Merging a source with duplicate keys — The MERGE fails. Deduplicate first.
- An unconditional WHEN NOT MATCHED BY SOURCE DELETE with a partial source — Deletes every target row missing from the batch.
- No pruning predicate on huge targets — The whole target is scanned and many files rewritten.
Key takeaways
- MERGE applies inserts, updates and deletes in one atomic commit.
- WHEN NOT MATCHED BY SOURCE handles target rows missing from the source.
- Each target row may match only one source row: deduplicate the source.
- Cost is driven by how many files are rewritten; prune and cluster.
Interview prep
THE QUESTION
"Design an upsert of a daily CDC feed into a 5 TB Delta table."
Avoid: MERGE without deduplicating the source. Two source rows matching one target row fail the MERGE.
Follow-ups · answer out loud, then open
Follow-up"What does WHEN NOT MATCHED BY SOURCE do?"
Scenario"A MERGE of 10,000 changed rows into a 5 TB table rewrites 2 TB. Why, and how do you fix it?"
Trap"MERGE is atomic, so running it twice is harmless."
Check yourself
3 questionsTwo source rows match the same target row. What happens?
Show the answer
The MERGE fails. The update would be ambiguous, so the MERGE raises an error.
Which clause deletes target rows that are not in the source?
Show the answer
WHEN NOT MATCHED BY SOURCE THEN DELETE. NOT MATCHED BY SOURCE targets rows absent from the source.
What usually dominates the cost of a copy-on-write MERGE?
Show the answer
Rewriting whole files that contain matched rows. Each touched file is rewritten in full.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Changing data · lesson 2 of 3 · 8 min readSlowly changing dimensions (SCD Type 2)
Keep the full history of a dimension with one MERGE per batch, and the edge cases that break it.
Related lessons
dropDuplicatesData lake & lakehouse · 6 min read
Copy-on-write vs merge-on-readData lake & lakehouse · 5 min read
Change Data Feed
Previous: Constraints and generated columns
Primary sources: Delta: upsert with MERGE · Iceberg: Spark writes (MERGE INTO)