Delta Lake
Follow a Delta transaction from data files to the commit log. Practice merges, time travel, recovery, and table maintenance.
How Delta works
A Delta table is a directory containing Parquet data files and a _delta_log/ folder. Every write adds a numbered JSON commit file (00000000000000000000.json, ...01.json) that records which files were added and removed. Every 10 commits (by default) Delta writes a checkpoint Parquet file summarizing the state, so readers do not replay every JSON file.
- A reader reads the log to find the current set of files, then reads only those. That snapshot gives isolation.
- Updates and deletes do not modify Parquet files in place. They write new files and mark old ones as removed (copy-on-write), or use deletion vectors to mark deleted rows without rewriting files (faster writes).
- Old files stay on storage until
VACUUM, which makes time travel possible.
Versions
Every committed write creates exactly one new version, whatever the number of rows. One INSERT with ten rows is one version; ten separate INSERT statements are ten versions. Schema changes (SET TBLPROPERTIES, CHANGE COLUMN) are versions too.
Databricks recommends referring to Delta tables by their fully qualified name (catalog.schema.table) rather than by file path. Names go through Unity Catalog permissions, lineage and auditing; paths bypass the table abstraction. Tables in other formats lack Delta's transactional guarantees and optimizations.
Creating and writing tables
CREATE TABLE main.silver.customers (
id BIGINT NOT NULL, name STRING, country STRING, updated_at TIMESTAMP
); -- Delta is the default format
CREATE OR REPLACE TABLE main.silver.orders AS -- CTAS: schema from the query
SELECT * FROM main.bronze.orders WHERE order_id IS NOT NULL;
INSERT INTO main.silver.customers VALUES (1, 'Ada', 'UK', current_timestamp());
INSERT OVERWRITE main.silver.daily SELECT ...; -- replace all data, keep table and history
UPDATE main.silver.customers SET country = 'GB' WHERE country = 'UK';
DELETE FROM main.silver.customers WHERE id = 1;
| Command | Behavior |
|---|---|
CREATE OR REPLACE TABLE ... AS SELECT | Replaces data and schema; keeps history (new version) |
INSERT OVERWRITE | Replaces data; the new data must match the existing schema |
DROP TABLE then CREATE | Loses history; avoid |
CREATE TABLE t2 LIKE t copies the definition only, no data. CREATE TABLE t (...) USING ICEBERG creates a managed Iceberg table in Unity Catalog.
Reset scripts: DROP TABLE IF EXISTS t does not fail when the table is missing; CREATE TABLE IF NOT EXISTS skips creation when it exists.
Write gotchas seen in the labs
CREATE TABLE OR REPLACEis a syntax error. The order isCREATE OR REPLACE TABLE.- Without a column list,
INSERT ... VALUESmust supply every column in order ("not enough data columns: target has 3, inserted 2"). Name the columns:INSERT INTO tasks (project_id, name) VALUES (1, 'x'). - An
id BIGINT GENERATED ALWAYS AS IDENTITYcolumn rejects explicit values; omit it.GENERATED BY DEFAULT AS IDENTITYaccepts explicit values. INSERT OVERWRITEtruncates then inserts: a 20 row table overwritten with 9 rows has 9 rows.DELETE FROM twithout aWHEREclause deletes every row (a new table version; time travel still works until VACUUM).
Writing files instead of a table
INSERT OVERWRITE DIRECTORY '/Volumes/main/exports/out/orders'
USING PARQUET
SELECT * FROM main.silver.orders; -- writes files, not a table
LOAD DATA INPATH ... INTO TABLE exists only for legacy Hive SerDe tables. Use COPY INTO or Auto Loader instead.
Keys, defaults and DDL gotchas
CREATE TABLE main.todos.projects (
id BIGINT GENERATED ALWAYS AS IDENTITY NOT NULL,
name STRING,
CONSTRAINT projects_pk PRIMARY KEY (id)
);
CREATE TABLE main.todos.completions (
id BIGINT GENERATED ALWAYS AS IDENTITY NOT NULL,
project_id BIGINT NOT NULL,
created_at TIMESTAMP DEFAULT current_timestamp(),
CONSTRAINT completions_pk PRIMARY KEY (id),
CONSTRAINT completions_project_fk FOREIGN KEY (project_id) REFERENCES main.todos.projects (id)
) TBLPROPERTIES ('delta.feature.allowColumnDefaults' = 'supported');
INSERT INTO main.todos.completions (project_id) VALUES (1); -- list columns explicitly
- An identity column is not a primary key by itself. Declare
PRIMARY KEYexplicitly; its columns must beNOT NULL. - A
FOREIGN KEYcan only reference columns that carry aPRIMARY KEYconstraint. - PK and FK are informational: inserting a
project_idthat does not exist succeeds. OnlyNOT NULLandCHECKreject writes. - Column
DEFAULTneeds the table featuredelta.feature.allowColumnDefaults = 'supported'. - On an existing table you cannot add a column with a default or with
NOT NULLin one step:ALTER TABLE t ADD COLUMN c TIMESTAMP, thenALTER TABLE t ALTER COLUMN c SET DEFAULT current_timestamp(). ALTER COLUMNis not supported on identity columns; recreate the table instead.
"A foreign key constraint will stop orphan rows" is false in Databricks. Use CHECK, NOT NULL, pipeline expectations or a join-based validation if you must reject them.
MERGE (upsert)
MERGE INTO main.silver.customers AS t
USING updates AS s
ON t.id = s.id
WHEN MATCHED AND s.op = 'DELETE' THEN DELETE
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *
WHEN NOT MATCHED BY SOURCE THEN DELETE; -- optional: delete rows missing from source
MERGE fails if multiple source rows match the same target row, so deduplicate the source first. MERGE is the standard way to apply CDC and avoid duplicate inserts.
MERGE does not allow a column list on an alias: USING (VALUES ...) AS s(id, name) fails. Put the column names inside a subquery, or use a table or temporary view as the source:
MERGE INTO main.app.tasks t
USING (SELECT * FROM VALUES (1, 'Plan sprint') AS v(project_id, name)) s
ON t.name = s.name AND t.project_id = s.project_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT (project_id, name) VALUES (s.project_id, s.name);
Multi-statement transactions
Every single Delta write (INSERT, UPDATE, DELETE, MERGE) is already an ACID transaction. Grouping several statements so they commit or roll back together uses the classic syntax:
BEGIN TRANSACTION;
UPDATE main.bank.accounts SET balance = balance - 100 WHERE id = 1;
UPDATE main.bank.accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- or ROLLBACK; a failing statement aborts the whole transaction
In Databricks, multi-statement transactions are a newer capability for Unity Catalog managed tables and are not enabled in every workspace. If you see "Multi-statement transactions are not enabled for this workspace", run the statements individually. Verify the current status in the docs before relying on it.
Time travel
DESCRIBE HISTORY main.silver.customers; -- versions, timestamps, operation, user
SELECT * FROM main.silver.customers VERSION AS OF 3;
SELECT * FROM main.silver.customers TIMESTAMP AS OF '2026-11-01';
SELECT * FROM main.silver.customers@v3; -- shorthand
RESTORE TABLE main.silver.customers TO VERSION AS OF 3; -- roll back; creates a new version
spark.read.option("versionAsOf", 3).table("main.silver.customers")
Time travel works only while the old data files still exist (VACUUM) and the log entries are retained (delta.logRetentionDuration, default 30 days).
DESCRIBE HISTORY output
DESCRIBE HISTORY columns you should recognize: version, timestamp, userName, operation (WRITE, MERGE, DELETE, OPTIMIZE, RESTORE, CREATE TABLE...), operationParameters, notebook, clusterId, readVersion, operationMetrics (rows and files added or removed).
RESTORE forms
RESTORE TABLE main.hr.employee TO VERSION AS OF 1;
RESTORE TABLE main.hr.employee TO TIMESTAMP AS OF '2026-11-01T00:00:00';
RESTORE TABLE main.hr.employee TO TIMESTAMP AS OF current_timestamp() - INTERVAL 1 HOUR;
The two clause forms are VERSION AS OF n and TIMESTAMP AS OF expr, used after the table name in SELECT and after TO in RESTORE TABLE t TO .... Expect a "which statement is valid" question.
Maintenance
| Command | Purpose |
|---|---|
OPTIMIZE t | Compacts many small files into larger ones (bin-packing). Fixes the "small files problem". |
OPTIMIZE t ZORDER BY (col) | Legacy: co-locates related values in files to improve data skipping on filter columns. Not compatible with liquid clustering. |
VACUUM t [RETAIN n HOURS] | Deletes data files no longer referenced by the table and older than the retention threshold. Default 7 days (168 hours). After vacuum you cannot time travel before that point. |
ANALYZE TABLE t COMPUTE STATISTICS FOR ALL COLUMNS | Collects statistics for the optimizer |
DESCRIBE DETAIL t | Location, format, number of files, size, partitioning, clustering columns |
DESCRIBE EXTENDED t | Columns plus metadata such as Type (MANAGED or EXTERNAL), Location, Owner |
OPTIMIZE in practice
OPTIMIZEbin-packs small files toward a target of about 1 GB per file.OPTIMIZE t WHERE date >= '2026-11-01'limits compaction to a subset (partition columns only).- Manual maintenance practice: run OPTIMIZE as a separate scheduled job (daily or weekly), on compute-optimized workers. On Unity Catalog managed tables, predictive optimization does this automatically (Troubleshooting and optimization).
VACUUM in practice
- Run
VACUUMregularly and after heavyDELETE,UPDATEorMERGEactivity to control storage cost. - Vacuuming with less than 7 days requires disabling a safety check (
spark.databricks.delta.retentionDurationCheck.enabled = false) and risks breaking long-running readers. VACUUM ... DRY RUNlists files it would delete.
Other Delta statements
| Statement | What it does |
|---|---|
CONVERT TO DELTA parquet.`/path` | Converts an existing Parquet table or directory to Delta in place (writes a transaction log, no data copy) |
FSCK REPAIR TABLE t | Removes log entries for data files that no longer exist in storage (for example, deleted manually) |
GENERATE symlink_format_manifest FOR TABLE t | Writes manifest files so engines such as Presto or Athena can read the table. Legacy; UniForm is the current interoperability option |
REORG TABLE t APPLY (PURGE) | Rewrites files to physically remove soft-deleted data: rows marked by deletion vectors and columns dropped with ALTER TABLE DROP COLUMN |
CACHE SELECT * FROM t WHERE ... | Preloads the selected data into the disk cache on the workers' local SSDs |
The video author reports seeing GENERATE, OPTIMIZE, RESTORE and VACUUM. Know what each does and the RESTORE ... TO VERSION AS OF / TIMESTAMP AS OF syntax.
Data layout: partitioning, Z-order, liquid clustering
- Partitioning (
PARTITIONED BY (date)) splits data into folders. Only useful for very large tables on low-cardinality columns (such as date). Over-partitioning creates tiny files. - Data skipping: Delta stores min/max statistics per file for the first 32 columns, and skips files that cannot match a filter.
- Z-order (
OPTIMIZE t ZORDER BY (col), legacy): Z-order on high-cardinality columns used in filters (many distinct values, such ascustomer_id). Partition only on low-cardinality columns of very large tables. The video advises keepingZORDER BYto 4 columns or fewer, because each extra column dilutes the effect. - Liquid clustering (
CLUSTER BY (col1, col2)) replaces partitioning and Z-order for new tables. Keys can be changed later without rewriting all data. Clustering happens incrementally onOPTIMIZE.CLUSTER BY AUTOlets Databricks pick keys from query patterns (needs predictive optimization). Details in Troubleshooting and optimization.
CREATE TABLE main.gold.events (...) CLUSTER BY (customer_id, event_date);
ALTER TABLE main.gold.events CLUSTER BY (event_date); -- change keys
ALTER TABLE main.gold.events CLUSTER BY NONE; -- remove
OPTIMIZE main.gold.events; -- cluster new data
OPTIMIZE main.gold.events FULL; -- recluster everything
Other Delta features
- Schema enforcement and evolution: see Data integrity.
ALTER TABLE t ADD COLUMNS (c STRING). Column mapping enables rename and drop of columns. - Generated columns:
event_date DATE GENERATED ALWAYS AS (CAST(ts AS DATE)). Identity columns:id BIGINT GENERATED ALWAYS AS IDENTITY. - Change Data Feed:
ALTER TABLE t SET TBLPROPERTIES (delta.enableChangeDataFeed = true), then read row-level changes withtable_changes('t', 2)(columns_change_type,_commit_version,_commit_timestamp). - Clones:
CREATE TABLE t2 DEEP CLONE tcopies data and metadata (independent copy, good for backups).SHALLOW CLONEcopies only metadata and points at the source files (cheap, good for testing). - Table properties:
TBLPROPERTIESsuch asdelta.deletedFileRetentionDuration,delta.logRetentionDuration,delta.enableDeletionVectors. - Uniform / Iceberg: Delta tables can be read as Apache Iceberg by other engines, and Unity Catalog supports managed Iceberg tables.
Delta outside Databricks (optional)
Delta Lake is open source and runs on plain Apache Spark. Spark 4.x needs Java 17 or later and pairs with Delta 4.x built for Scala 2.13 (artifact io.delta:delta-spark_2.13; before Delta 3.0 it was called delta-core).
pyspark --packages io.delta:delta-spark_2.13:4.0.0 \
--conf "spark.sql.extensions=io.delta.sql.DeltaSparkSessionExtension" \
--conf "spark.sql.catalog.spark_catalog=org.apache.spark.sql.delta.catalog.DeltaCatalog"
# the shell (like a Databricks notebook) already provides the SparkSession as spark
spark.range(0, 5).write.format("delta").save("/tmp/delta-table")
spark.read.format("delta").load("/tmp/delta-table").show()
spark.range(5, 10).write.format("delta").mode("overwrite").save("/tmp/delta-table")
from delta.tables import DeltaTable
DeltaTable.forPath(spark, "/tmp/delta-table").update("id % 2 = 0", {"id": "id + 100"})
The local Spark UI (port 4040) shows the same Jobs, Stages, Storage and Environment tabs you open from a Databricks cluster.
Exam recap
- Transaction log = source of truth; ACID; optimistic concurrency.
- Time travel syntax,
RESTORE,DESCRIBE HISTORY. - VACUUM default 7 days and its effect on time travel.
- OPTIMIZE for small files; liquid clustering preferred over partitioning and Z-order.
- CTAS vs INSERT OVERWRITE vs CREATE OR REPLACE; MERGE syntax.
Explain a historical result
A table had 12 rows at version 4. One committed write appends three rows, and nothing else changes. Predict the row counts from a current read and a read at version 4.
Check your reasoning
The current table has 15 rows. A VERSION AS OF 4 query still sees 12 while the log and files for that snapshot remain available.
Product reference
Delta Lake quiz
Answer 12 questions. Check each answer for an explanation.