Skip to content
Silver 7 min read · All formats 3 practice problems ↓

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

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.

PySparkSpark SQL
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

ClauseApplies toCan
WHEN MATCHED [AND cond]Target rows with a matching source rowUPDATE or DELETE
WHEN NOT MATCHED [AND cond]Source rows with no target matchINSERT
WHEN NOT MATCHED BY SOURCE [AND cond]Target rows with no source matchUPDATE 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 * and INSERT * 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

Spark joins the source with the target (inner join on the ON condition) to find which target files contain matching rows. With file statistics and partition predicates in the ON condition, many files are skipped here.

Step 2 · rewrite

For copy-on-writecopy-on-write: Applying an update by rewriting the affected files at once: slower writes, simple reads. Learn more → tables, each touched file is read in full, the updates and deletes are applied, and a new file is written with all its rows, changed or not. New inserts are written to new files. With deletion vectorsdeletion vector: A small list of the deleted row positions in one data file, so a delete does not rewrite the file. Learn more →, unchanged rows need not be rewritten.

Step 3 · commit

One commit removes the touched files and adds the rewritten and new ones. Readers see all of the merge or none of it.

Cost · what dominates

Rewriting whole files to change a few rows in each. Updating 10,000 rows spread over 10,000 files rewrites 10,000 files. Clustering the target by the merge key, and adding partition or date predicates to the ON clause, keeps the touched set small.

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:

PySparkSpark SQL
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.

Production patternPySpark · An upsert with every clause, and the duplicate-source error
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 whenNotMatchedBySourceDelete removed 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."

Deduplicate the feed to the latest change per key (row_number over key ordered by sequence), then MERGE with matched update/delete and not-matched insert. Performance: predicates in ON to prune, clustering by key, deletion vectors, small source. Mention atomicity (one commit), the duplicate-source error, and idempotency if the job reruns.

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?"
It acts on target rows with no matching source row, typically to delete or flag rows that disappeared from a full snapshot. Always add a condition (for example a date range) or it touches the whole target.
Scenario"A MERGE of 10,000 changed rows into a 5 TB table rewrites 2 TB. Why, and how do you fix it?"
The changed keys are spread across most files, so copy-on-write rewrites every touched file. Add partition or date predicates to the ON clause so fewer files are candidates, cluster the table by the merge key, and enable deletion vectors so updates mark rows instead of rewriting whole files.
Trap"MERGE is atomic, so running it twice is harmless."
Each run is atomic, but not automatically idempotent. A second run of an insert-only MERGE is harmless, but an update that increments a counter or appends history rows applies twice. Design the logic to give the same result on rerun.

Check yourself

3 questions

Two 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 read
Slowly 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

Previous: Constraints and generated columns

Primary sources: Delta: upsert with MERGE · Iceberg: Spark writes (MERGE INTO)