Sub topic 9
Changing Rows with UPDATE and DELETE
This chapter covers how Delta Lake changes existing rows in place with UPDATE and DELETE. It assumes you can write basic SQL (SELECT, INSERT, WHERE) and that you know a Delta table is a set of Parquet data files plus a transaction log. Both the log and the table you created earlier are used here.
Why row-level changes need special handling
Parquet files are immutable. A plain data lake cannot edit one row inside a file. Delta Lake adds a transaction log on top of the files, so it can offer standard UPDATE and DELETE statements. Each statement commits as one atomic table version. Readers see the table either before the change or after it, never halfway through.
The examples use the main.sales.orders table from earlier chapters:
UPDATE main.sales.orders
SET status = 'shipped'
WHERE order_id = 1001;
DELETE FROM main.sales.orders
WHERE status = 'cancelled';The first statement changes one column on the rows that match the predicate. The second removes every matching row. Both statements use a WHERE clause. Without one, UPDATE changes every row and DELETE removes every row.
What happens inside a commit
Delta does not edit a Parquet file. It rewrites the files that contain matching rows. The steps are:
- Delta scans the table to find the data files that contain rows matching the predicate.
- It reads those files and writes new files. The new files hold the changed rows and the untouched rows from the same files.
- It commits one new JSON entry to the transaction log. The entry marks the old files as removed and the new files as added.
The old files stay in storage. They are no longer part of the current table version, but they are still there for time travel until VACUUM deletes them.
Because the unit of rewriting is a file, the cost depends on how many files hold matching rows, not on how many rows match. Changing one row in a 1 GB file rewrites that whole file.
UPDATE in detail
The general form is:
UPDATE main.sales.orders
SET status = 'shipped', amount = amount * 1.05
WHERE customer_id = 7 AND status = 'new';Points to know:
- Expressions can reference other columns. In
amount * 1.05, the right side is evaluated against the old value of the row. - Multiple columns update together. All assignments in one
SETclause apply in the same commit. - Constraints are checked. The
NOT NULLandCHECKconstraints from the schema chapter apply. Settingorder_idtoNULL, oramountto a negative number whenpositive_amountexists, fails the whole statement and no new version is created. - Types must fit. Assigning a string to a
DECIMAL(10,2)column follows Spark's casting rules. In ANSI mode, a value that does not cast raises an error. - Subqueries are limited. You can use a subquery in the
WHEREclause withINorEXISTS. For anything more complex, such as updating from values in another table, useMERGE.
An UPDATE that matches zero rows succeeds and commits nothing meaningful. You can check how many rows changed by looking at the result of the statement. Databricks returns num_affected_rows.
SELECT * FROM main.sales.orders WHERE order_id = 1001;DELETE in detail
DELETE FROM removes rows that satisfy a predicate:
DELETE FROM main.sales.orders
WHERE order_ts < '2024-01-01';Delta has a metadata-only fast path. When the predicate lines up with a partition column, or when whole files match, Delta can drop files from the log without rewriting any data. This is cheap. A predicate on an ordinary column often forces file rewrites, because matching and non-matching rows share files.
A DELETE removes data from the current table version only. The deleted rows are still in the older data files. This matters for privacy requests such as a GDPR erasure. The rows remain readable through time travel until VACUUM removes the old files after the retention period.
Deletion vectors
Rewriting a whole file to change one row is wasteful. Databricks supports deletion vectors to reduce that cost. A deletion vector is a small side file that records which rows in a data file are no longer valid. With deletion vectors enabled on a table:
DELETEwrites a deletion vector and leaves the original Parquet file alone.UPDATEandMERGEcan mark old rows as deleted and write only the new row versions.- Readers apply the deletion vector when they scan the file, so deleted rows do not appear.
- The physical rewrite is deferred. It happens later, for example during
OPTIMIZE.
You can turn the feature on for one table with a table property:
ALTER TABLE main.sales.orders
SET TBLPROPERTIES (delta.enableDeletionVectors = true);Whether the feature is on by default depends on the runtime and on your workspace settings, so check the table with DESCRIBE DETAIL or SHOW TBLPROPERTIES before you rely on it. Enabling it also upgrades the table protocol. Older Delta readers that do not understand deletion vectors can no longer read the table.
Checking the effect of a change
Every UPDATE and DELETE adds a row to the table history. DESCRIBE HISTORY shows the operation and metrics:
DESCRIBE HISTORY main.sales.orders LIMIT 5;Look at the operation column (UPDATE or DELETE) and at operationMetrics. The metrics include the number of rows updated or deleted, the number of files added and removed, and the number of rewritten rows. Comparing files removed against rows changed tells you how much rewriting a statement caused. If a statement changed 10 rows but rewrote 400 files, your predicate does not line up with the data layout.
Using the Python API
You can run the same operations from Python with DeltaTable. The API takes SQL expressions as strings or Column objects:
from delta.tables import DeltaTable
orders = DeltaTable.forName(spark, "main.sales.orders")
orders.update(
condition="order_id = 1001",
set={"status": "'shipped'"},
)
orders.delete("status = 'cancelled'")Note the quoting in set. The value is a SQL expression, so a string literal needs its own single quotes inside the Python string. Writing "shipped" without the inner quotes makes Delta look for a column named shipped.
Common errors and how to avoid them
| Problem | Cause | Fix |
|---|---|---|
| Whole table changed | Missing `WHERE` clause | Run a `SELECT COUNT(*)` with the same predicate first |
| Constraint violation error | New value breaks `NOT NULL` or `CHECK` | Fix the value or the predicate. The statement is rolled back |
| Concurrent modification exception | Another writer changed the same files | Retry, or narrow the predicate so the writers touch different files |
| Deleted data still readable | Old files remain until `VACUUM` | Run `VACUUM` after the retention period |
| Slow `UPDATE` on a large table | Predicate matches rows spread over many files | Use partitioning or liquid clustering on the filter column, or enable deletion vectors |
| Python update sets a column to another column | String value without inner quotes | Quote literals inside the expression, as in `"'shipped'"` |
Conflicts with concurrent writers
Delta uses optimistic concurrency control. Two writers can work at the same time. When the second one tries to commit, Delta checks whether the first writer changed files that the second one read. If they overlap, the second commit fails with a conflict exception, and the table stays consistent. Two UPDATE statements on different partitions usually do not conflict. Two statements that touch the same files do. A later chapter covers this in detail.
A safe workflow for risky changes
For a change you cannot easily undo, follow these steps:
- Run a
SELECTwith the exactWHEREclause and check the row count. - Note the current version from
DESCRIBE HISTORY. - Run the
UPDATEorDELETE. - Check the metrics in
DESCRIBE HISTORY. - If the result is wrong, run
RESTORE TABLE ... TO VERSION AS OF nwith the version you noted.
Step 5 works only while the old data files still exist, so do not run VACUUM on the table until you are sure of the change.
Exercise
You run DELETE FROM main.sales.orders WHERE status = 'cancelled' on a table without deletion vectors. The history shows 12 rows deleted but 300 files rewritten. What does this tell you, and what would you do about it? Also, can someone still read the deleted rows afterwards?
Show answer
Cancelled rows are spread across many files, so Delta rewrote every file that held even one of them. The cost follows the number of files touched, not the number of rows. To reduce it, cluster or partition the table on a column related to the filter, or enable deletion vectors so Delta records the deleted rows instead of rewriting files. Yes, the deleted rows can still be read with time travel (VERSION AS OF) until VACUUM removes the old data files after the retention period, which is 7 days by default.