Delta Lake
When to Use
Load this skill when the user needs to:
- Create and manage Delta tables (DDL, partitioning, table properties)
- Write DML: INSERT, UPDATE, DELETE, MERGE (upsert, SCD2, CDC)
- Compact files (OPTIMIZE), apply data skipping (Z-ORDER BY)
- Vacuum stale files, time travel, restore snapshots
- Evolve schemas without breaking existing readers
- Read Delta tables in streaming or batch mode
SparkSession Setup
python
from pyspark.sql import SparkSession
spark = (
SparkSession.builder
.appName("delta-pipeline")
.config("spark.jars.packages", "io.delta:delta-spark_2.13:3.2.0")
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
.config("spark.sql.catalog.spark_catalog",
"org.apache.spark.sql.delta.catalog.DeltaCatalog")
.getOrCreate()
)
Table DDL
CREATE TABLE
sql
-- Managed table (Hive/Unity catalog manages location)
CREATE TABLE silver.orders (
order_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
amount DECIMAL(18,2),
status STRING,
event_time TIMESTAMP,
dt DATE GENERATED ALWAYS AS (CAST(event_time AS DATE)),
_ingest_ts TIMESTAMP
)
USING DELTA
PARTITIONED BY (dt)
TBLPROPERTIES (
'delta.minReaderVersion' = '2',
'delta.minWriterVersion' = '5',
'delta.columnMapping.mode' = 'name', -- allows DROP/RENAME columns
'delta.autoOptimize.optimizeWrite' = 'true', -- right-size files on write
'delta.autoOptimize.autoCompact' = 'true', -- background compaction
'delta.deletedFileRetentionDuration' = 'interval 7 days',
'delta.logRetentionDuration' = 'interval 30 days',
'delta.dataSkippingNumIndexedCols' = '32'
);
-- External (unmanaged) table — survives DROP TABLE
CREATE TABLE silver.orders
USING DELTA
LOCATION 's3a://datalake/silver/orders/'
PARTITIONED BY (dt);
CREATE TABLE AS SELECT (CTAS)
sql
CREATE TABLE silver.orders_clean
USING DELTA
PARTITIONED BY (dt)
AS
SELECT order_id, user_id, CAST(amount AS DECIMAL(18,2)), status,
event_time, CAST(event_time AS DATE) AS dt
FROM bronze.orders_raw
WHERE order_id IS NOT NULL;
Python API
python
from delta.tables import DeltaTable
from pyspark.sql.types import *
DeltaTable.createIfNotExists(spark) \
.tableName("silver.orders") \
.addColumn("order_id", LongType(), nullable=False) \
.addColumn("user_id", LongType(), nullable=False) \
.addColumn("amount", DoubleType()) \
.addColumn("status", StringType()) \
.addColumn("event_time", TimestampType()) \
.addColumn("dt", DateType(),
generatedAlwaysAs="CAST(event_time AS DATE)") \
.partitionedBy("dt") \
.property("delta.autoOptimize.autoCompact", "true") \
.execute()
DML
INSERT / APPEND
python
# DataFrame append
df.write.format("delta").mode("append").saveAsTable("silver.orders")
df.write.format("delta").mode("append").save("s3a://datalake/silver/orders/")
# SQL INSERT
spark.sql("""
INSERT INTO silver.orders
SELECT order_id, user_id, amount, status, event_time
FROM bronze.orders_raw
WHERE dt = '2024-01-15'
""")
Partition Overwrite
python
# Static overwrite — replaces ALL partitions
df.write.format("delta").mode("overwrite").save(path)
# Dynamic overwrite — replaces only partitions present in df
df.write.format("delta") \
.mode("overwrite") \
.option("partitionOverwriteMode", "dynamic") \
.saveAsTable("silver.orders")
# replaceWhere — overwrite a predicate-defined range
df.write.format("delta") \
.mode("overwrite") \
.option("replaceWhere", "dt = '2024-01-15'") \
.save(path)
UPDATE
python
from delta.tables import DeltaTable
dt = DeltaTable.forName(spark, "silver.orders")
# Update specific rows
dt.update(
condition="status = 'pending' AND event_time < current_timestamp() - INTERVAL 7 DAYS",
set={"status": "'expired'", "_ingest_ts": "current_timestamp()"},
)
sql
UPDATE silver.orders
SET status = 'expired', _ingest_ts = current_timestamp()
WHERE status = 'pending' AND event_time < current_timestamp() - INTERVAL 7 DAYS;
DELETE
python
dt.delete("status = 'cancelled' AND dt < '2023-01-01'")
sql
DELETE FROM silver.orders
WHERE status = 'cancelled' AND dt < '2023-01-01';
MERGE — Upsert Pattern
python
from delta.tables import DeltaTable
source = spark.table("staging.orders_latest")
target = DeltaTable.forName(spark, "silver.orders")
(
target.alias("t")
.merge(source.alias("s"), "t.order_id = s.order_id")
.whenMatchedUpdate(set={
"status": "s.status",
"amount": "s.amount",
"event_time": "s.event_time",
"_ingest_ts": "current_timestamp()",
})
.whenNotMatchedInsert(values={
"order_id": "s.order_id",
"user_id": "s.user_id",
"amount": "s.amount",
"status": "s.status",
"event_time": "s.event_time",
"_ingest_ts": "current_timestamp()",
})
.execute()
)
sql
MERGE INTO silver.orders AS t
USING (
SELECT order_id, user_id, amount, status, event_time
FROM staging.orders_latest
) AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET
t.status = s.status,
t.amount = s.amount,
t.event_time = s.event_time,
t._ingest_ts = current_timestamp()
WHEN NOT MATCHED THEN INSERT (order_id, user_id, amount, status, event_time, _ingest_ts)
VALUES (s.order_id, s.user_id, s.amount, s.status, s.event_time, current_timestamp());
MERGE — SCD Type 2
python
from pyspark.sql.functions import current_timestamp, lit, expr
# Source: new/changed dimension records
new_data = spark.table("staging.customers_latest")
# Separate into: records that changed + new records (via union trick)
staged = new_data.selectExpr(
"customer_id", "name", "email", "city",
"md5(concat_ws('|', name, email, city)) AS row_hash",
)
# Step 1: Expire changed current records
(
DeltaTable.forName(spark, "silver.dim_customers").alias("t")
.merge(staged.alias("s"), "t.customer_id = s.customer_id AND t.is_current = true AND t.row_hash != s.row_hash")
.whenMatchedUpdate(set={
"is_current": "false",
"valid_to": "current_timestamp()",
})
.execute()
)
# Step 2: Insert new current versions
(
new_data.alias("s")
.join(
spark.table("silver.dim_customers").filter("is_current = true").alias("t"),
"s.customer_id = t.customer_id", "left_anti" # not in current → new
)
.union(
new_data.alias("s").join(
spark.table("silver.dim_customers").filter("is_current = false").alias("t"),
expr("s.customer_id = t.customer_id AND s.row_hash != t.row_hash")
).select("s.*")
)
.withColumn("is_current", lit(True))
.withColumn("valid_from", current_timestamp())
.withColumn("valid_to", lit(None).cast("timestamp"))
.write.format("delta").mode("append").saveAsTable("silver.dim_customers")
)
MERGE — CDC (Change Data Capture)
python
from pyspark.sql.functions import col
# CDC source: rows with op_type = 'I' / 'U' / 'D'
cdc_df = spark.table("staging.orders_cdc")
# Keep only last operation per key
from pyspark.sql.window import Window
from pyspark.sql.functions import row_number
latest_cdc = (
cdc_df
.withColumn("rn", row_number().over(
Window.partitionBy("order_id").orderBy(col("cdc_ts").desc())
))
.filter("rn = 1")
.drop("rn")
)
(
DeltaTable.forName(spark, "silver.orders").alias("t")
.merge(latest_cdc.alias("s"), "t.order_id = s.order_id")
.whenMatchedDelete(condition="s.op_type = 'D'")
.whenMatchedUpdate(
condition="s.op_type IN ('U', 'I')",
set={"status": "s.status", "amount": "s.amount", "event_time": "s.cdc_ts"},
)
.whenNotMatchedInsert(
condition="s.op_type != 'D'",
values={
"order_id": "s.order_id",
"user_id": "s.user_id",
"amount": "s.amount",
"status": "s.status",
"event_time": "s.cdc_ts",
},
)
# Delete from target rows no longer in source (full refresh only)
# .whenNotMatchedBySourceDelete()
.execute()
)
Schema Evolution
python
# Append new columns automatically
df.write.format("delta") \
.option("mergeSchema", "true") \
.mode("append") \
.save(path)
# Replace entire schema on overwrite
df.write.format("delta") \
.option("overwriteSchema", "true") \
.mode("overwrite") \
.save(path)
# Session-level auto-merge (for MERGE INTO schema evolution)
spark.conf.set("spark.databricks.delta.schema.autoMerge.enabled", "true")
sql
-- Add column
ALTER TABLE silver.orders ADD COLUMN discount DECIMAL(10,2) AFTER amount;
-- Rename column (requires columnMapping.mode = 'name')
ALTER TABLE silver.orders RENAME COLUMN user_id TO customer_id;
-- Drop column (requires columnMapping.mode = 'name')
ALTER TABLE silver.orders DROP COLUMN legacy_field;
-- Change type (widening only: INT → LONG, FLOAT → DOUBLE, etc.)
ALTER TABLE silver.orders ALTER COLUMN amount TYPE DOUBLE;
-- Add comment
ALTER TABLE silver.orders ALTER COLUMN status COMMENT 'Order lifecycle status';
Column mapping (delta.columnMapping.mode = 'name') must be enabled for RENAME and DROP. Enable on existing table:
sql
ALTER TABLE silver.orders
SET TBLPROPERTIES (
'delta.minReaderVersion' = '2',
'delta.minWriterVersion' = '5',
'delta.columnMapping.mode' = 'name'
);
OPTIMIZE & Z-ORDER BY
sql
-- Compact small files in a specific partition
OPTIMIZE silver.orders WHERE dt = '2024-01-15';
-- Compact + cluster by frequently filtered columns (max 4 cols)
OPTIMIZE silver.orders WHERE dt >= '2024-01-01'
ZORDER BY (status, user_id);
python
from delta.tables import DeltaTable
dt = DeltaTable.forName(spark, "silver.orders")
# Compaction only
dt.optimize().executeCompaction()
# Compaction + Z-ORDER on a partition
dt.optimize().where("dt = '2024-01-15'").executeZOrderBy("status", "user_id")
Z-ORDER tips:
- Use on columns with high cardinality that appear in
WHERE / JOIN predicates. - Max 4 columns (effectiveness degrades beyond that).
- Re-run after significant data ingestion; not automatic.
- Combine with partition pruning: filter on partition column first, Z-ORDER for within-partition skipping.
Auto Optimize (set once, runs automatically):
sql
ALTER TABLE silver.orders
SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true', -- right-sizes files during write
'delta.autoOptimize.autoCompact' = 'true' -- background compaction after write
);
VACUUM
Removes files no longer referenced by any table version.
sql
-- Dry run — see what would be deleted
VACUUM silver.orders DRY RUN;
-- Delete files older than 7 days (default retention)
VACUUM silver.orders;
-- Custom retention (minimum 168 hours = 7 days enforced by default)
VACUUM silver.orders RETAIN 240 HOURS;
python
dt = DeltaTable.forName(spark, "silver.orders")
dt.vacuum(retentionHours=240)
# Bypass minimum retention (DANGEROUS — disables safety check)
spark.conf.set("spark.databricks.delta.retentionDurationCheck.enabled", "false")
dt.vacuum(retentionHours=0)
spark.conf.set("spark.databricks.delta.retentionDurationCheck.enabled", "true")
Rule: never VACUUM with retention < active streaming query lag. Streaming readers hold references to old files; VACUUM removes them → StreamingQueryException.
Time Travel
sql
-- Query by version
SELECT * FROM silver.orders VERSION AS OF 42;
-- Query by timestamp
SELECT * FROM silver.orders TIMESTAMP AS OF '2024-01-15 10:00:00';
-- Show full history
DESCRIBE HISTORY silver.orders;
DESCRIBE HISTORY silver.orders LIMIT 5;