MERGE and schema changes
Part of the free LogicWiz Data Engineering course, Module 13: The lakehouse on Databricks. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 6:20 on Wednesday and the run log has two red lines. Last night's MERGE into silver.orders took three hours: it rewrote 512 GB to change 40,000 orders, about 20 MB of data. And the 06:00 products load failed, because the catalogue team renamed a column in their export. Nora reads both and says: "Start with the three hours. Find out what MERGE touched."
You'll learn to
- Explain MERGE's two passes and predict which files it rewrites
- Work out why scattered keys make MERGE rewrite a whole table
- Guard a MERGE against duplicate keys and stale changes
- Tell schema enforcement, evolution and column mapping apart
Learn
Three ways to load a change file
Every night a change file lands. It holds orders that are new and orders that changed. There are three ways to load it into silver.orders:
- Append it. Fast, but order 1002 now has two rows,
shippedanddelivered, and every count over it is wrong. - Overwrite the whole table from a full extract. Correct, but you rewrite every row every night for a handful of changes.
- Upsert: update the rows whose key already exists, insert the rest. One row per order.
In SQL an upsert is written MERGE. Postgres has it, so you can run one right here. Delta has it too, and there the interesting part is what it does to files.
MERGE in Postgres
MERGE INTO silver_orders AS t
USING changes AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN
UPDATE SET status = s.status, updated_at = s.updated_at
WHEN NOT MATCHED THEN
INSERT (order_id, status, updated_at) VALUES (s.order_id, s.status, s.updated_at);
SELECT order_id, status, updated_at
FROM silver_orders
ORDER BY order_id;
silver_orders starts with orders 1001 to 1004. changes is the morning file: one changed order and one new one. The ON condition decides which rows match.
What MERGE did, row by row
| orderid | Target before | Source | Target after | Why |
|---|---|---|---|---|
| 1001 | cancelled | none | cancelled | not in the source: untouched |
| 1002 | shipped | delivered | delivered | matched: updated |
| 1003 | delivered | none | delivered | untouched |
| 1004 | cancelled | none | cancelled | untouched |
| 1081 | none | placed | placed | not matched: inserted |
One statement, both actions, and the key stays unique. Run it twice and the second run changes nothing: MERGE on a key is idempotent.
MERGE reads the table twice
So far, so cheap. Now the three hours.
A Parquet file cannot be edited, so Delta cannot change one row in place. Think of a printed phone book: to fix one name, you reprint the whole page.
Delta's MERGE therefore reads the target table twice:
- Find the pages. It joins the source with the target on the
ONcondition, reading only the columns it needs, and notes which files hold a matching row. - Reprint them. It reads those files again and writes every row of them into new files: updated, deleted or copied unchanged, plus the inserts.
- Commit. One new version removes each old file and adds each new one.
Changing data this way is called copy-on-write.
One changed order, one whole file
A change file with one updated and one new order is merged into a table of two files: pass one finds the file that holds the match, pass two writes that whole file again with the changes, and a commit swaps the old file for the new one.
Before. The table has two files of 40 orders each. The change file holds one changed order, 1002, and one new order, 1081.
Pass 1: find the touched files. An inner join on
order_idfinds 1002 inpart-00000and nothing inpart-00001. This pass also counts matches: two source rows for one target row stop the MERGE right here.Pass 2: write the file again.
part-00000is read a second time and outer-joined with the source. Every row goes intopart-00002: 1 updated, 39 copied unchanged, plus the 1 insert.Commit. One new version removes
part-00000and addspart-00002. The table has 81 rows. The old file stays in the folder for time travel.
Follow the amber file. The source is read in both passes, so it must give the same rows both times: Delta saves a copy of a source it cannot prove repeatable, such as one that reads non-Delta files or calls a random function. A MERGE that only inserts skips pass 2 and appends.
Run the same MERGE and watch the files
import minidelta
t = minidelta.DeltaTable('lake/orders')
t.write("SELECT order_id, status, updated_at FROM 'data/orders.csv' WHERE order_id <= 1040")
t.write("SELECT order_id, status, updated_at FROM 'data/orders.csv' WHERE order_id > 1040")
changes = [
{'order_id': 1002, 'status': 'delivered', 'updated_at': '2025-06-05 09:00:00'},
{'order_id': 1081, 'status': 'placed', 'updated_at': '2025-06-15 08:00:00'},
]
t.merge(changes, on='order_id')
print(t.history()[0]['operationMetrics'])
print(t.files())
Find numTargetRowsCopied in the output: 39 rows were written again only because they share a file with order 1002. The metric names are the ones Databricks shows in DESCRIBE HISTORY.
Remember: MERGE's cost follows the files it touches, not the rows it changes.
Why 40,000 changes cost 512 GB
Now scale it up. silver.orders has 1 billion rows in 4,000 files of 128 MB. That is 512 GB. Last night's file changed 40,000 orders, and their keys are scattered at random.
Think of throwing 40,000 darts at 4,000 boxes. Each box gets about 10 darts. Will any box stay empty?
- A file escapes one change with chance 1 - 1/4,000.
- It escapes all 40,000 with chance (1 - 1/4,000)^40,000 ≈ e^-10 ≈ 0.00005.
- Files expected to escape: 4,000 × 0.00005 ≈ 0.2.
So no file escapes. All 4,000 files, 512 GB, are rewritten to change 0.004% of the rows. That is the first group in the next picture.
The same 40,000 changes, scattered and clustered
Two groups of eight boxes, each box standing for 500 files: with scattered keys all eight are rewritten; clustered by order date, seven are skipped and only part of the last one is rewritten.
Each small box stands for 500 of the 4,000 files, oldest orders first. Compare how much is amber in the first group and in the second.
Put the changes next to each other
Now look at the second group. The table is now clustered by order date: orders with nearby dates sit in the same files (Lesson 13.4 shows how). Every order in last night's file is from the last 7 days, out of 730 days of history.
- Files touched: about 4,000 × 7 / 730 ≈ 38.
- Data rewritten: 38 files of 128 MB, under 5 GB.
One more step is needed. Pass 1 has to be told it may skip the old files, with a filter on the target inside ON: AND t.order_date >= '2025-06-01'.
Use that filter only when every change is known to fall in the range. A source row outside it counts as not matched, gets inserted, and that order is now in the table twice.
What MERGE writes for 40,000 changed orders
Bars compare the gigabytes a MERGE rewrites: 512 when the keys are scattered over every file, about 4.9 when the table is clustered by date with a target filter, and about 0.02 with deletion vectors.
Read the bars top to bottom: each one is at least a hundred times shorter than the one above it. Row size: 128 MB / 250,000 rows = 512 bytes, so 40,000 changed rows are about 20 MB.
Mark the row, keep the file
The green bar is barely visible. It comes from a different trick.
Deletion vectors. Instead of copying a touched file, MERGE writes a small bitmap next to it that says which row positions no longer count. Then it writes only the new versions of the changed rows. In DESCRIBE HISTORY, numTargetRowsCopied drops towards zero.
There is a catch. Deletion vectors cut what is written, not what is scanned. Pass 1 still reads the key columns of every file it cannot skip, and readers filter out the marked rows until OPTIMIZE (Lesson 13.4) rewrites the files.
Databricks adds a second saving, low shuffle merge, on by default: unchanged rows skip the shuffle, so they keep the file layout you gave them.
MERGE INTO on Databricks
Runs on Databricks:
MERGE INTO workspace.silver.orders AS t
USING workspace.bronze.order_changes AS s
ON t.order_id = s.order_id
WHEN MATCHED AND s.updated_at > t.updated_at THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;
num_affected_rows num_updated_rows num_deleted_rows num_inserted_rows
2 1 0 1
Look at the AND s.updated_at > t.updated_at on the fourth line: the next card says why it is there. UPDATE SET * and INSERT * copy every column by name, a Delta shortcut. WHEN NOT MATCHED BY SOURCE THEN DELETE also exists, for rows that disappeared from a full snapshot; it forces a right outer join in pass 1, so it reads more.
The trap: two classic MERGE bugs. First, the same key twice in the source. Delta stops with Cannot perform Merge as multiple source rows matched and attempted to modify the same target row in the Delta table in possibly conflicting ways, because two rows would update one target row. Deduplicate the source first, keeping the latest row per key (Module 2). Second, changes that arrive late or are replayed. Without AND s.updated_at > t.updated_at, an old change overwrites a newer row and the order goes back in time.
The 06:00 failure: the table said no
Now the second red line. The catalogue export used to have a price column. This morning it has unit_price_usd and a new brand, and the load failed.
That failure is the table protecting itself. A Delta table checks every write against its own list of columns, the schema in its metaData. This is called schema enforcement:
- a column the table does not have: rejected
- a type that does not fit (text into a number): rejected
- a column the write leaves out: allowed, it becomes NULL
The error starts A schema mismatch detected when writing to the Delta table and prints both schemas.
The catalogue export changed
import duckdb
import minidelta
t = minidelta.DeltaTable('lake/products')
t.write("SELECT * FROM 'data/products.csv'")
try:
t.write("SELECT * FROM 'data/products_v2.csv'")
except minidelta.SchemaMismatch as e:
print('rejected:', e)
t.write("SELECT * FROM 'data/products_v2.csv'", merge_schema=True)
print(t.read().columns)
t.register('products')
print(duckdb.sql("""
SELECT COUNT(*) FILTER (WHERE price IS NULL) AS no_price,
COUNT(*) FILTER (WHERE unit_price_usd IS NULL) AS no_unit_price
FROM products
""").fetchall())
Rejected first, then let in on purpose. merge_schema=True stands for Delta's .option("mergeSchema", "true"): you opt in, for this one write, to adding new columns. That is schema evolution. The second write added unit_price_usd and brand to the schema in a metaData action, in the same commit as the data. Now read the last line of output.
After evolution: one fact under two names
| Rows from | price | unitpriceusd | brand |
|---|---|---|---|
| the old export (20 rows) | 59.99, 14.99, ... | NULL | NULL |
| the new export (20 rows) | NULL | 59.99, 14.99, ... | Northwind, Acme, ... |
brand really is new, so adding it is right. But unit_price_usd is price renamed, and evolution cannot know that: it adds a column and leaves half of each one empty. A rename is yours to handle: map the new name back to the old one in the load, or rename the table column on purpose.
Remember: enforcement says no to surprise columns. Evolution adds columns when you ask. Neither can see a rename.
Rename a column without rewriting files
So how do you rename price on purpose? Parquet files store column names inside them. Without help, a rename would mean rewriting every file, so ALTER TABLE ... RENAME COLUMN fails with Column rename is not supported for your Delta table and tells you to enable column mapping.
Column mapping (delta.columnMapping.mode = 'name') gives each column a permanent physical name and id. The files use the physical name. The name you query is only a label, the logical name. Renaming or dropping a column then changes one line of metadata and no data file.
The price: it needs a newer protocol, so older readers lose the table (Lesson 13.2).
A rename with column mapping
Three layers: the name you query, the mapping kept in the schema, and the Parquet files. Renaming price to unit_price_usd changes the first two and leaves the files untouched.
Before the rename. You query
price. The schema maps that label to a physical column, and the files store the values under the physical name.After
RENAME COLUMN price TO unit_price_usd. One commit with a newmetaDataaction changes the label. The physical column and every data file stay exactly as they were.
Watch the Parquet files box: it never changes. A rename with column mapping is a metadata-only commit.
Read the changes, not the table
One last thing while you are in this table. The gold tables built from silver do not need all billion rows each night. They need what changed since their last run.
Set delta.enableChangeDataFeed = true and Delta keeps that list for you: the change data feed. A commit that updates or deletes rows also writes small change files under _change_data/. Each change row carries a _change_type: insert, delete, update_preimage (the row before) or update_postimage (the row after).
You read it by version. SELECT * FROM table_changes('workspace.silver.orders', 5) returns every change from version 5 on, with _commit_version and _commit_timestamp.
Ask a table what changed
import minidelta
t = minidelta.DeltaTable('lake/orders')
t.write("SELECT order_id, status, updated_at FROM 'data/orders.csv' WHERE order_id <= 1005")
t.merge([
{'order_id': 1002, 'status': 'delivered', 'updated_at': '2025-06-05 09:00:00'},
{'order_id': 1081, 'status': 'placed', 'updated_at': '2025-06-15 08:00:00'},
], on='order_id') # version 1
t.delete('order_id = 1004') # version 2
for c in t.changes(1, 'order_id'):
print(c['_commit_version'], c['_change_type'], c['order_id'], c['status'])
Four lines for two commits: an update is two rows, before and after. Real Delta writes these change rows as it commits; minidelta works them out by comparing each version with the one before, which gives the same answer more slowly. The feed has limits: it covers only commits made after it was switched on, and its files age out with the table's retention, so a consumer that falls too far behind must rebuild.
Numbers to remember
| Thing | Value | What it means |
|---|---|---|
| numTargetRowsCopied, numTargetFilesRemoved | In DESCRIBE HISTORY | Rows copied only because they shared a file, and files rewritten. Compare them before and after a fix |
| Deletion vectors for MERGE | Databricks Runtime 12.2 LTS with Photon, 14.3 LTS without | Matched rows are marked in a bitmap on the same file; only the new row versions are written |
| Low shuffle merge | On by default | Unmodified rows are processed separately, without a shuffle, and keep their layout, Z-order included. Only updated and inserted rows may need a later OPTIMIZE |
| .option("mergeSchema", "true") | Per write | Adds new columns |
| MERGE WITH SCHEMA EVOLUTION INTO ... | Databricks Runtime 15.2 and above | The same, for a MERGE |
| .option("overwriteSchema", "true") | With an overwrite | Replaces the schema, for a type change |
| A schema change | One metaData action in the commit | Lesson 13.8 shows it can fail concurrent writers |
| delta.columnMapping.mode = 'name' | Reader version 2, writer version 5 (or the columnMapping feature) | Names may contain spaces and ,;{}()=. A stream reading the table fails on a rename or drop unless it tracks schema changes with schemaTrackingLocation |
| delta.enableChangeDataFeed = true | Change files under changedata/, listed by cdc actions | A commit that only appends or removes whole files writes no extra copy: its add and remove actions already say what changed |
What changed at SwiftKart
Two fixes go in before 8:00. The products load maps unit_price_usd back to price before it writes, and adds brand on purpose. The MERGE gets a deduplicated source and only updates a row when the change is newer.
One fix is still open. Until silver.orders is clustered by order date, the MERGE will keep touching every file, and the filter in ON has nothing to skip. Each rewrite also leaves the old files behind in the folder.
Lesson 13.4 does both jobs: it packs and sorts the files so changes sit together, then clears out the old ones.
In one line
MERGE reads the target twice and rewrites every file that holds a matched row, so its cost follows touched files, not changed rows; a Delta table rejects surprise columns, adds them when you ask, and needs column mapping to rename one.
Interview corner
Walk me through what Delta does when you run a MERGE.
Pass 1 inner-joins the source with the target on the ON condition, reading only the needed columns, to find which target files hold a matched row; it also fails if two source rows match one target row. Pass 2 reads those touched files again and outer-joins them with the source, writing updated, deleted, copied and inserted rows to new files. Then one commit removes the touched files and adds the new ones. An insert-only MERGE skips the rewrite, and because the source is read twice Delta materialises it when it cannot prove it deterministic.
A daily MERGE that changes 0.01% of rows rewrites the whole table. Why, and what do you do?
Cost follows touched files, and with keys scattered over 4,000 files, 40,000 changes leave an expected 4,000 × e^-10, essentially zero files, untouched. I cluster the table by the column the changes concentrate on, usually a date, and add a target filter to the ON condition when every change is known to fall in that range so pass 1 can skip files. Deletion vectors then mark matched rows instead of copying files, and low shuffle merge keeps the unchanged rows' layout. I verify with numTargetFilesRemoved and numTargetRowsCopied.
Schema enforcement, schema evolution and column mapping: what is each?
Enforcement rejects writes with extra columns or incompatible types and fills missing columns with NULL. Evolution is opting in per write: mergeSchema, or MERGE WITH SCHEMA EVOLUTION, adds new columns in a metaData action; overwriteSchema replaces it for type changes. Neither can see a rename. Column mapping gives each column a physical name, so RENAME and DROP COLUMN are metadata-only, at the cost of a protocol upgrade to reader 2 and writer 5 and schema tracking for streams.
What is the change data feed, and what are its limits?
With delta.enableChangeDataFeed on, commits that update or delete rows also write change files under _change_data, so table_changes returns inserts, deletes and update pre- and post-images per version; appends and whole-file removes are read straight from the add and remove actions. Downstream jobs read changes since their last processed version instead of rescanning. It only covers commits after it was enabled, and its files are vacuumed with the table, so a consumer that falls behind the retention must rebuild from a full read.