Sub topic 10
Upserting with MERGE
An upsert combines two actions in one statement. If a row already exists, it is updated. If it doesn't exist, it is inserted. In Delta Lake the MERGE INTO statement does this, and it can also delete rows. This chapter assumes you can write UPDATE and DELETE statements on Delta tables, you know how JOIN ... ON works, and you know that every Delta write is one atomic commit in the transaction log.
Why MERGE exists
Data pipelines rarely deliver clean, one-time inserts. A source system sends changed orders, corrected values, and cancellations. If you only append, you get duplicates. If you run UPDATE and then INSERT as two statements, a failure between them leaves the table half-changed, and a reader can see that state.
MERGE compares a source (a table, view, or query) with a target Delta table, row by row. You write rules for each case. All the changes from one MERGE commit as a single table version, so readers see either none of them or all of them.
The basic upsert
This is the statement from the chapter plan. It updates orders that exist and inserts the rest.
MERGE INTO main.sales.orders AS t
USING main.sales.orders_updates AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;The parts work like this:
MERGE INTOnames the target. It must be a Delta table.USINGnames the source. It can be a table, a view, or a subquery.ONis the match condition. Each source row is tested against target rows.WHEN MATCHEDruns when a source row finds a target row.WHEN NOT MATCHEDruns when a source row finds no target row. It is also writtenWHEN NOT MATCHED BY TARGET.SET *andINSERT *map source columns to target columns by name.
Clause order and conditions
You can add several WHEN clauses and attach an extra condition to each with AND. Delta evaluates the clauses in the order you write them, and the first one whose condition is true is applied. Put the most specific clauses first.
MERGE INTO main.sales.orders AS t
USING main.sales.orders_updates AS s
ON t.order_id = s.order_id
WHEN MATCHED AND s.status = 'cancelled' THEN DELETE
WHEN MATCHED AND s.order_ts > t.order_ts THEN UPDATE SET *
WHEN NOT MATCHED AND s.status <> 'cancelled' THEN INSERT *;This statement does three things:
- It deletes a target order when the source says it was cancelled.
- It updates a matched order only when the source row is newer, so a late-arriving old record cannot overwrite fresh data.
- It inserts unmatched rows, except cancelled ones, which would have nothing to cancel.
A matched row that fails every condition is left unchanged. Only the last WHEN MATCHED clause in a statement may omit its condition. If there are several matched clauses, every one but the last needs an AND condition.
Explicit column lists
SET * is convenient but depends on column names. When you want control, list the columns.
MERGE INTO main.sales.orders AS t
USING main.sales.orders_updates AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET
t.status = s.status,
t.amount = s.amount
WHEN NOT MATCHED THEN INSERT (order_id, customer_id, order_ts, amount, status)
VALUES (s.order_id, s.customer_id, s.order_ts, s.amount, s.status);Here an update touches only status and amount. Other columns of a matched row keep their values.
The duplicate-source error
Delta refuses to update one target row from two different source rows, because the result would depend on arbitrary order. If two source rows match the same target row, the merge fails with an error saying multiple source rows matched.
The fix is to deduplicate the source before merging. Keep one row per key, usually the latest.
CREATE OR REPLACE TEMP VIEW latest_updates AS
SELECT *
FROM main.sales.orders_updates
QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY order_ts DESC) = 1;
MERGE INTO main.sales.orders AS t
USING latest_updates AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;Duplicates in the target for the same key are a different problem. They are not an error, but each duplicate target row gets updated. Duplicate target keys usually mean an earlier append went wrong.
Handling rows missing from the source
WHEN NOT MATCHED BY SOURCE fires for target rows that no source row matched. Use it when the source is a full snapshot and rows absent from it should be removed or flagged.
MERGE INTO main.sales.orders AS t
USING main.sales.orders_snapshot AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *
WHEN NOT MATCHED BY SOURCE AND t.status = 'new' THEN DELETE;The extra AND condition limits the damage. Without it, a partial source batch would delete every target row it didn't mention.
The same merge from Python
The DeltaTable API expresses the same logic. Use it when the source is a DataFrame built in code.
from delta.tables import DeltaTable
target = DeltaTable.forName(spark, "main.sales.orders")
(target.alias("t")
.merge(updates_df.alias("s"), "t.order_id = s.order_id")
.whenMatchedUpdateAll(condition="s.order_ts > t.order_ts")
.whenNotMatchedInsertAll()
.execute())Each when... method matches a SQL clause. The optional condition argument is the AND condition. Explicit versions exist too: whenMatchedUpdate(set={...}), whenMatchedDelete(), and whenNotMatchedInsert(values={...}). Nothing runs until .execute(). The method returns nothing useful, so read the outcome from the table history.
Checking what a merge did
After a merge, DESCRIBE HISTORY shows an entry with operation MERGE. Its operationMetrics column reports counts such as numTargetRowsInserted, numTargetRowsUpdated, numTargetRowsDeleted, and numTargetRowsCopied. If an upsert reports zero updates when you expected many, the ON condition is the first thing to check, for example a type mismatch or trailing spaces in a string key.
DESCRIBE HISTORY main.sales.orders LIMIT 1;Schema evolution during a merge
By default, UPDATE SET * and INSERT * do not add new source columns to the target. To let a merge add them, enable automatic schema evolution for the session before running it.
spark.conf.set("spark.databricks.delta.schema.autoMerge.enabled", "true")With this setting on, new source columns are added to the target schema when you use * clauses. Clauses with explicit column lists do not evolve the schema. Enabling it makes the setting apply to every merge in the session, so turn it off again for jobs where an unexpected column should fail the run.
Performance and concurrency
A merge works in two phases. It first finds which target files contain matching rows, then it rewrites those files. Cost therefore depends on how many target files the ON condition touches.
- Key the merge on a selective column. Merging on a column that is random across files rewrites many files.
- Add a target-side predicate to the
ONcondition when you know the affected range, such ast.event_date >= '2026-12-01'. Delta can then skip files outside that range. - Keep the source small and deduplicated. A source that is much larger than needed slows the join.
- Cluster or partition the target by the columns used in the merge predicate, as covered in the data layout chapter.
A predicate that limits the target has a trap. If the real match lies outside the range you wrote, the source row finds no match and is inserted as a duplicate. Add a range only when the source rows are guaranteed to fall inside it.
Concurrent merges that rewrite the same files conflict, and one fails with a concurrent modification exception. Reduce the chance by making the ON condition narrow, so different jobs touch different files. The next chapters cover how to retry.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Source has two rows for one key | Error: multiple source rows matched | Deduplicate with `ROW_NUMBER()` and `QUALIFY` |
| Join key has mismatched types or whitespace | Everything inserts, nothing updates | Cast or trim in the source before merging |
| Unconditional `NOT MATCHED BY SOURCE` delete | Target rows vanish after an incremental run | Add a condition, or use only with full snapshots |
| Range predicate in `ON` misses real matches | Duplicate rows appear | Make sure all source keys fall in the range |
| Merge on `*` with new source columns | Error about missing columns | Enable `autoMerge` or list columns explicitly |
Exercise
A nightly job merges a batch of order changes into main.sales.orders using ON t.orderid = s.orderid. The job fails with an error saying multiple source rows matched the same target row. What caused it, and how do you fix it without changing the target table?
Show answer
The batch contains more than one row for at least one orderid, so a single target row would be updated by several source rows. Deduplicate the source before the merge so each orderid appears once. For example, create a view that keeps the latest row per key with ROWNUMBER() OVER (PARTITION BY orderid ORDER BY order_ts DESC) = 1 in a QUALIFY clause, and merge from that view.
Exercise
You add WHEN NOT MATCHED BY SOURCE THEN DELETE to a merge that loads an hourly batch of 500 changed orders. What happens to the rest of the table, and what should you change?
Show answer
Every target row that is not in the 500-row batch is deleted, because none of them match a source row. Remove the clause, or use it only when the source is a full snapshot, and add a condition such as AND t.status = 'new' to limit which rows it can delete.