Part 9 · Query execution · Chapter 34
MERGE, UPDATE and DELETE internals
How row-level operations execute on Delta and Iceberg: finding touched files, copy-on-write rewrites, merge-on-read with deletion vectors, and what each does to the read set and conflicts.
After this chapter you should be able to:
- Trace a Delta MERGE through its phases and predict which files it reads, rewrites and removes.
- Explain DELETE's three cases and UPDATE's two write paths.
- Compare copy-on-write and merge-on-read for a workload, in Delta and in Iceberg.
Parquet files are immutable, and both table formats track files, not rows. So a statement that changes three rows has two choices. It can rewrite every file that holds one of those rows (copy-on-write), or it can write the new rows and record which old rows no longer count (merge-on-read, with deletion vectors or delete files). This chapter traces how Delta’s Spark connector and Spark’s DataSource V2 rewrite rules, which Iceberg uses, run MERGE, UPDATE and DELETE, and what each choice costs.
The simulator in src/sim/delta/merge.ts runs Delta’s executors on an 8-file table partitioned by day. Its tests check every combination of MERGE clauses, with and without deletion vectors, against a direct evaluation of the MERGE definition.
Delta MERGE
MergeIntoCommand describes its algorithm in three phases:[Delta MergeIntoCommand.scala]
Phase 1: Find the input files in target that are touched by the rows that satisfy the condition and verify that no two source rows match with the same target row.
Phase 2: Read the touched files again and write new files with updated and/or inserted rows.
Phase 3: Use the Delta protocol to atomically remove the touched files and add the new files.
runMerge opens one transaction and picks an executor from the clauses:[runMerge]
val mergeActions = {
if (isInsertOnly && spark.conf.get(DeltaSQLConf.MERGE_INSERT_ONLY_ENABLED)) {
writeOnlyInserts(spark, deltaTxn, filterMatchedRows = true, numSourceRowsMetric = "numSourceRows")
} else {
val (filesToRewrite, deduplicateCDFDeletes) = findTouchedFiles(spark, deltaTxn)
if (filesToRewrite.nonEmpty) {
if (shouldWriteDeletionVectors) {
writeAllChanges(..., writeUnmodifiedRows = false) ++ writeDVs(spark, deltaTxn, filesToRewrite)
} else {
writeAllChanges(..., writeUnmodifiedRows = true) ++ filesToRewrite.map(_.remove)
}
} else {
writeOnlyInserts(spark, deltaTxn, filterMatchedRows = false, ...)
}
}
}
(trimmed). Insert-only MERGE (only WHEN NOT MATCHED clauses) is a single job. InsertOnlyMergeExecutor skips target files with the merge condition, runs a left anti join of the source against the target, and appends what is left. Nothing is removed.[InsertOnlyMergeExecutor.scala] spark.databricks.delta.merge.optimizeInsertOnlyMerge.enabled defaults to true.[DeltaSQLConf] If phase 1 finds no touched files at all, the classic executor ends the same way: every source row is unmatched, so it writes the inserts and rewrites nothing.
Q1. In Delta's classic MERGE executor without deletion vectors, what are the phases?
Q2. How does Delta run a MERGE with only WHEN NOT MATCHED THEN INSERT?
Phase 1: finding touched files
ClassicMergeExecutor.findTouchedFiles does three things in one Spark job.[findTouchedFiles]
It chooses candidate files. Without a NOT MATCHED BY SOURCE clause, it calls deltaTxn.filterFiles(getTargetOnlyPredicates(spark)). Only conjuncts of the ON condition that reference the target alone take part. s.id = t.id references the source, so it skips nothing: open-source Delta reads every file of the table in phase 1 for a plain key-equality MERGE. Adding AND t.day >= '2026-11-20' to the ON clause, when you know the source only touches recent days, lets data skipping and partition pruning drop files. It also changes the meaning, since older target rows can no longer match. With a NOT MATCHED BY SOURCE clause, it calls filterFiles(Seq(Literal.TrueLiteral)), because unmatched target rows anywhere may need to change.
It joins and records files. The target plan gets two columns, monotonically_increasing_id() as a row id and input_file_name(). The join is inner, or right outer when there is a NOT MATCHED BY SOURCE clause. A non-deterministic UDF adds the file name of each joined row to a SetAccumulator when matchedPredicate holds. That predicate is the OR of the MATCHED clause conditions when there are only MATCHED clauses, and true otherwise.
It checks for multiple matches. The same job groups by row id and counts matches. More than one source row for a target row makes an update ambiguous, so throwErrorOnMultipleMatches fails the MERGE, unless the only MATCHED clause is an unconditional DELETE, where deleting a row twice is still one delete.[throwErrorOnMultipleMatches]
The candidate files become the transaction’s read set (chapter 10). The open-source conflict checker evaluates only the partition part of read predicates, so on an unpartitioned table a MERGE conflicts with any concurrent commit that adds files, unless that commit is a blind append under the default WriteSerializable level. A NOT MATCHED BY SOURCE MERGE reads the whole table, so on a partitioned table too it conflicts with every such commit. See the commit protocol.
Q1. MERGE INTO t USING s ON s.id = t.id, where t has 10,000 files and s has 5 rows. How many target files does phase 1 read in open-source Delta?
Q2. Two source rows match the same target row in a MERGE with WHEN MATCHED THEN UPDATE. What happens?
Q3. What does adding WHEN NOT MATCHED BY SOURCE THEN DELETE do to the cost of a Delta MERGE?
Phase 2: rewriting with copy-on-write
Without deletion vectors, writeAllChanges(writeUnmodifiedRows = true) reads only the touched files and joins them with the source again.[writeAllChanges] The join is full outer, or right outer (source on the left, every target row kept) when there are only MATCHED clauses and merge.optimizeMatchedOnlyMerge.enabled is on. Each joined row goes through the clauses:
- a matched row with
UPDATEproduces the new row; withDELETE, nothing; - an unmatched target row is copied, or dropped by
NOT MATCHED BY SOURCE THEN DELETE; - an unmatched source row is inserted by
NOT MATCHED THEN INSERT.
The output is written as new files, and the commit removes every touched file. The cost is proportional to the size of the touched files, not to the number of changed rows. One changed row in a 1 GB file rewrites 1 GB.
MERGE with deletion vectors
shouldWritePersistentDeletionVectors is true when the command’s *.deletionVectors.persistent conf is on (the default) and DeletionVectorUtils.deletionVectorsWritable holds: the protocol supports the deletionVectors table feature and delta.enableDeletionVectors is set.[shouldWritePersistentDeletionVectors][deletionVectorsWritable][DeltaSQLConf] Phase 2 then splits in two, as the executor’s scaladoc says: “2.a. Read the touched files again and only write modified and new rows”, and “2.b. Read the touched files and generate deletion vectors for the modified rows”.[ClassicMergeExecutor scaladoc]
- Identify touched files Find target rows and files affected by the MERGE clauses.
- Rewrite the files Write updated and inserted rows together with unchanged rows from touched files.
- Commit replacements Remove the old file entries and add the new ones.
- Write new and changed rows Keep surviving rows in their existing Parquet files.
- Publish deleted positions Update the vectors for retained files so reads skip the old rows.
Phase 2a uses writeUnmodifiedRows = false, so the join can be stricter: inner for matched-only, left outer (keeping source rows) without NOT MATCHED BY SOURCE, right outer without NOT MATCHED, full outer otherwise. Phase 2b, writeDVs, joins again, filters with generateFilterForModifiedRows (matched rows that satisfy a MATCHED clause, plus unmatched target rows that satisfy a NOT MATCHED BY SOURCE clause), and builds a set of row indexes per file.[writeDVs][generateFilterForModifiedRows]
The new bitmap is combined with any existing deletion vector. A file whose rows are all deleted is removed outright; otherwise the commit removes the file’s old entry and adds the same path with the new DV.[DMLWithDeletionVectorsHelper] That works because the protocol keys a logical file by both: “The primary key for the entry of a logical file in the set of files is a tuple of the data file’s path and a unique id describing the DV.”[PROTOCOL.md] Chapter 13 covers the DV format, and readers apply it as in deletion vectors and row tracking.
The write cost is now proportional to the changed rows. The price is paid by readers, who must load and apply DVs, and by maintenance: OPTIMIZE or purge rewrites files to drop deleted rows.
Q1. With deletion vectors enabled on the table, how does a Delta MERGE that updates 3 rows in a file of 1,000,000 rows change that file? (Select all.) (select all that apply)
Q2. When do Delta's MERGE, UPDATE and DELETE write deletion vectors instead of rewriting files?
UPDATE and DELETE
DeleteCommand has three cases.[DeleteCommand.scala]
- No condition. Remove every file.
- The condition uses only partition columns.
splitMetadataAndDataPredicatesleaves no data predicates, sofilterFiles(metadataPredicates)returns the files to remove, and no data file is read. This is a metadata-only delete. - Anything else.
filterFileswith the condition uses partition values and statistics to find candidates, a scan of the candidates finds the files with matching rows, and then:- with DVs,
DMLWithDeletionVectorsHelper.findTouchedFilesbuilds row-index bitmaps andprocessUnmodifiedDatawrites the DV actions;[DeleteCommand: DV path] - without DVs, each touched file is rewritten with the filter
Not(EqualNullSafe(cond, Literal.TrueLiteral)). A row whose condition is null is kept, as SQL requires.[DeleteCommand: rewrite]
- with DVs,
UpdateCommand follows the same shape: “Identify the affected files”, “Scan affected files, apply the updates”, and write new files while removing the affected ones.[UpdateCommand.scala] With DVs, it writes only the updated rows and marks the old ones, exactly like MERGE phase 2.
Q1. DELETE FROM t WHERE day = '2026-11-01' on a table partitioned by day. What does Delta read?
Q2. When DELETE rewrites a file, which rows does it keep?
Iceberg row-level operations
For DataSource V2 tables, Spark rewrites MERGE, UPDATE and DELETE in the analyzer, and the table chooses the shape. RewriteMergeIntoTable asks the table for a row-level operation. If the operation is SupportsDelta, Spark builds a WriteDelta plan; otherwise it builds a ReplaceData plan that replaces whole groups (files).[Spark RewriteMergeIntoTable]
Iceberg picks the operation from a table property per command, write.delete.mode, write.update.mode and write.merge.mode. Each is copy-on-write by default; merge-on-read requires format v2 or later.[Iceberg configuration][SparkRowLevelOperationBuilder]
Copy-on-write (ReplaceData). The target is joined with the source (left outer, or full outer when there are NOT MATCHED actions), and every read target row that no action changes is carried over. To avoid rewriting the whole table, Spark turns the ON condition into an EXISTS subquery over the source and passes it as a runtime group filter, when there is no NOT MATCHED BY SOURCE clause.[toGroupFilterCondition] Iceberg applies it to the copy-on-write scan, so only files with a matching row are read and replaced, which is the same outcome as Delta’s touched-file accumulator through a different mechanism (chapter 30 covers runtime filtering).
Merge-on-read (WriteDelta). The join type follows from which unmatched rows are needed, from inner to full outer.[buildWriteDeltaPlan] The output is a row delta: new rows go to data files and deleted or replaced rows become deletes keyed by file and position. For a v3 table, SparkWriteConf.deleteFileFormat returns Puffin, and the writer is a PartitioningDVWriter; for v2 it writes position delete files.[SparkWriteConf.deleteFileFormat][SparkPositionDeltaWrite] The spec requires a single vector per file: “there can be at most one deletion vector for a given data file in a snapshot. Writers must ensure that there is at most one deletion vector per data file and must merge new deletes with existing vectors or position delete files.”[Iceberg spec] Iceberg deletes covers how readers apply them.
Spark also turns an insert-only MERGE into a left anti join and an append for V2 tables, like Delta’s insert-only executor.[RewriteMergeIntoTable: insert-only] Each Iceberg command also has an isolation-level property, serializable by default, which decides what the commit validates against concurrent changes (Iceberg commits and concurrency).
Q1. An Iceberg table has default properties. How does Spark execute MERGE on it?
Q2. In a copy-on-write MERGE on a DataSource V2 table, how does Spark avoid rewriting every file?
Q3. In Iceberg format v3, a merge-on-read DELETE hits a data file that already has a deletion vector. What must the writer do?
Try it
The target table has days 1 to 4, two files per day, six rows per file, ids 1 to 48. Pick a statement and clauses. The lab shows each phase, which files were skipped, read and touched, the actions of the commit, and the table after it.
- With the default upsert, phase 1 reads all 8 files and touches 2. Copy-on-write writes 14 rows to change 5. Turn on deletion vectors: 5 rows are written and the two files get DVs.
- Check AND t.day >= 4 in ON: phase 1 reads 2 files. Switch the source to “1 changed row on each day”: the rows on days 1 to 3 no longer match, so they are inserted as duplicates.
- Add NOT MATCHED BY SOURCE DELETE: all 8 files are read and touched, even with the day predicate.
- Use the “id 44 twice” source with UPDATE, then with only
MATCHED DELETE. - Switch to DELETE:
day = 2removes two files without reading them,id IN (5, 30)rewrites or marks two files, andid BETWEEN 1 AND 6with DVs removes a whole file.
MERGE INTO t USING s ON s.id = t.id WHEN MATCHED THEN UPDATE SET v = s.v WHEN NOT MATCHED THEN INSERT *
Source rows: (40, day 4, 'b') (44, day 4, 'b') (47, day 4, 'b') (101, day 4, 'b') (102, day 4, 'b')
- Phase 1, findTouchedFiles. The ON clause has no target-only predicate, so no skipping. An inner join of the source with 8 files records the files of matched rows: 2 touched.
- Phase 2, writeAllChanges. A full outer join of the source with the 2 touched files only. Writes every surviving row of those files: 9 copied unchanged, 3 updated, 2 inserted.
- Commit. 3 actions in one commit. Rows changed: 5; data rows written: 14.
touched read, not touched skipped
{"add": {"path": "day=4/part-008", "numRecords": 14}} // copied, updated and inserted rows
{"remove": {"path": "day=4/part-006", "dataChange": true}}
{"remove": {"path": "day=4/part-007", "dataChange": true}}Target afterStruck-through ids are masked by a deletion vector; highlighted ids carry new values.
Summary
- Delta MERGE runs in two jobs: phase 1 joins source and target to find touched files and reject ambiguous multiple matches, and phase 2 joins the source with the touched files and writes the result. One commit removes and adds files.
- Phase 1 skips files only with target-only predicates in
ON. A plains.id = t.idreads the whole table;NOT MATCHED BY SOURCEalways does. - Insert-only MERGE is a left anti join and an append, with nothing removed.
- Copy-on-write cost follows the size of touched files. With deletion vectors, MERGE, UPDATE and DELETE write only changed rows and replace each touched file’s
(path, DV)entry. - DELETE with only partition predicates is metadata-only. A rewriting DELETE keeps rows where the condition is not true, including null.
- Iceberg chooses per command between copy-on-write (
ReplaceData, with a runtime group filter) and merge-on-read (WriteDelta, with position deletes in v2 and one deletion vector per file in v3). Copy-on-write is the default.
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 12 quiz questions.