Sub topic 10
Upserting with MERGE
This chapter assumes you can write basic SQL and PySpark, you have run UPDATE and DELETE on a Delta table, and you know that each commit creates a new table version in the transaction log. Here you will use MERGE to apply a batch of changes to a table in one atomic operation.
Why MERGE exists
An upsert updates rows that already exist and inserts rows that do not. With only INSERT and UPDATE you would need two statements, and a failure between them would leave the table half changed. MERGE INTO does both in a single commit, so readers see either the old version or the new one.
You supply three things:
- A target table to change.
- A source (a table, view or query) holding the incoming changes.
- A match condition that decides which source row corresponds to which target row.
A basic upsert in SQL
The source table orders_updates holds new and changed orders. Rows whose order_id already exists in the target are updated. All other rows are inserted.
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 *;UPDATE SET * and INSERT * map source columns to target columns by name. This is convenient, but it assumes the source has the columns you expect. If the source has extra columns, the statement fails unless schema evolution is enabled (see the schema chapter).
The same upsert in Python
The DeltaTable API expresses the same operation. It suits pipelines where the updates already live in a DataFrame.
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()
.whenNotMatchedInsertAll()
.execute())How MERGE works
Delta first finds the target files that contain rows matching the source. It rewrites those files with the updated rows and adds new files for inserted rows. It then records one commit that removes the old files and adds the new ones.
Because affected files are rewritten, a merge that touches rows spread across many files costs more than one that touches a few files. A selective ON condition keeps the work small.
Adding conditions and deletes
Each WHEN clause can have an extra condition. You can also delete matched rows. This example deletes cancelled orders, updates the rest only when the incoming data is newer, and inserts new orders that are not cancelled.
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 *;Clauses are evaluated in order, and the first one whose condition is true for a row is applied. Put the more specific conditions first.
Common errors
- Duplicate source keys. If two source rows match the same target row, the merge fails with an error about multiple source rows matching. Deduplicate the source first, for example by keeping the latest row per key with a window function.
- Unselective ON condition. If the condition does not use a key or a clustered column, Delta may scan and rewrite many files. Use the table's key and, where possible, a filter on partition or clustering columns.
- Schema mismatch.
UPDATE SET *andINSERT *need compatible columns. Name the columns explicitly when the source has extra or renamed fields. - Concurrent writers. Two merges that rewrite the same files can conflict, and one fails and must be retried.
Exercise
A MERGE fails because multiple source rows match a single target row. What is the cause, and how do you fix it?
Show answer
The source contains duplicate values for the join key in the ON condition, so one target row matches more than one source row and the result is ambiguous. Deduplicate the source before merging, for example by keeping one row per key (such as the latest by timestamp) using a window function or an aggregation.
Exercise
In a MERGE with clauses WHEN MATCHED AND s.status = 'cancelled' THEN DELETE and WHEN MATCHED THEN UPDATE SET *, why must the DELETE clause come first?
Show answer
Clauses are evaluated in order and the first one whose condition is true is applied. If the unconditional UPDATE came first, it would match every matched row, and the DELETE clause would never run.