Set up Delta with PySpark
$pip install pyspark==4.0.1 delta-spark==4.0.0
from delta import configure_spark_with_delta_pip
from pyspark.sql import SparkSession, functions as F
builder = (SparkSession.builder.appName("shopkart-delta").master("local[*]")
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
.config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog")
.config("spark.ui.showConsoleProgress", "false"))
spark = configure_spark_with_delta_pip(builder).getOrCreate() # adds the Delta jars
spark.sparkContext.setLogLevel("ERROR")
schema = ("order_id INT, customer_id INT, product_id INT, quantity INT, "
"unit_price DECIMAL(10,2), status STRING, order_ts TIMESTAMP")
orders = (spark.read.option("header", True).schema(schema).csv("data/orders/")
.dropna(subset=["order_id", "quantity"]))
orders.write.format("delta").mode("overwrite").save("out/delta/orders")
print(spark.read.format("delta").load("out/delta/orders").count(), "rows in the Delta table")5315 rows in the Delta tableTwo settings turn on Delta's SQL extension and catalog; configure_spark_with_delta_pip adds the Delta jars (downloaded once from Maven). Then .format("delta") reads and writes Delta tables.
import os
print(sorted(f for f in os.listdir("out/delta/orders/_delta_log") if f.endswith(".json")))['00000000000000000000.json']Version 0 is a single JSON file in _delta_log that lists the Parquet files making up the table. Every later change adds the next numbered file.
MERGE: the upsert
Two orders changed status and one new order arrived. MERGE updates matches and inserts the rest, in one atomic commit:
from delta.tables import DeltaTable
updates = spark.createDataFrame(
[(100002, "RETURNED"), (100003, "DELIVERED"), (200001, "PLACED")], ["order_id", "status"])
new_row = updates.filter("order_id = 200001").select(
"order_id", F.lit(5).alias("customer_id"), F.lit(3).alias("product_id"), F.lit(1).alias("quantity"),
F.lit(4999).cast("decimal(10,2)").alias("unit_price"), "status",
F.current_timestamp().alias("order_ts"))
source = updates.filter("order_id != 200001").join(
spark.read.format("delta").load("out/delta/orders").drop("status"), "order_id").unionByName(new_row)
target = DeltaTable.forPath(spark, "out/delta/orders")
(target.alias("t")
.merge(source.alias("s"), "t.order_id = s.order_id")
.whenMatchedUpdate(set={"status": "s.status"})
.whenNotMatchedInsertAll()
.execute())
spark.read.format("delta").load("out/delta/orders").filter(
F.col("order_id").isin(100002, 100003, 200001)).select("order_id", "status").orderBy("order_id").show()+--------+---------+
|order_id| status|
+--------+---------+
| 100002| RETURNED|
| 100003|DELIVERED|
| 200001| PLACED|
+--------+---------+(target.history()
.select("version", "operation", F.col("operationMetrics.numTargetRowsUpdated").alias("updated"),
F.col("operationMetrics.numTargetRowsInserted").alias("inserted"))
.show())+-------+---------+-------+--------+
|version|operation|updated|inserted|
+-------+---------+-------+--------+
| 1| MERGE| 2| 1|
| 0| WRITE| NULL| NULL|
+-------+---------+-------+--------+Version 1 records exactly what happened: 2 rows updated, 1 inserted. If the job had crashed halfway, nothing would have changed.
Time travel
v0 = spark.read.format("delta").option("versionAsOf", 0).load("out/delta/orders")
print("version 0:", v0.count(), "rows; order 100002 was", v0.filter("order_id = 100002").first()["status"])
print("latest :", spark.read.format("delta").load("out/delta/orders").count(), "rows")version 0: 5315 rows; order 100002 was DELIVERED
latest : 5316 rowsversionAsOf (or timestampAsOf) reads the table as it was. Use it to audit changes, reproduce an old report or recover from a bad write (RESTORE TABLE ... TO VERSION AS OF), as long as VACUUM hasn't deleted the old files.
Schema enforcement and evolution
bad = (new_row.withColumn("order_id", F.lit(200002)) # same columns and types as the table...
.withColumn("coupon", F.lit("DIWALI10"))) # ...plus one new column
bad = bad.withColumn("order_id", F.col("order_id").cast("int"))
try:
bad.write.format("delta").mode("append").save("out/delta/orders")
except Exception as e:
print(type(e).__name__, "->", str(e).splitlines()[0][:110])
bad.write.format("delta").mode("append").option("mergeSchema", "true").save("out/delta/orders")
print(spark.read.format("delta").load("out/delta/orders").columns)AnalysisException -> [_LEGACY_ERROR_TEMP_DELTA_0007] A schema mismatch detected when writing to the Delta table (Table ID: 508ad70a
['order_id', 'customer_id', 'product_id', 'quantity', 'unit_price', 'status', 'order_ts', 'coupon']The first append had an unexpected coupon column, so Delta refused it (schema enforcement): no half-broken table. With mergeSchema=true the change is intentional (schema evolution) and the column is added.
Keep tables fast: OPTIMIZE
# Many small files (each write adds some) -> compact them into fewer, bigger files
(DeltaTable.forPath(spark, "out/delta/orders").optimize().executeCompaction()
.select("metrics.numFilesAdded", "metrics.numFilesRemoved").show())+-------------+---------------+
|numFilesAdded|numFilesRemoved|
+-------------+---------------+
| 1| 9|
+-------------+---------------+Every write added files; OPTIMIZE compacted 9 of them into 1. On real tables with thousands of small files from streaming or frequent MERGEs, this makes reads much faster. VACUUM later deletes files no longer referenced (after the retention period).
| Command (PySpark API) | Does |
|---|---|
| df.write.format('delta').save(path) | Create/overwrite/append a Delta table |
| DeltaTable.forPath(spark, path).merge(...) | Upsert (update + insert, optionally delete) |
| DeltaTable.history() | All versions with metrics |
| read.option('versionAsOf', n) | Time travel |
| option('mergeSchema', 'true') | Allow new columns |
| DeltaTable.optimize().executeCompaction() | Compact small files |
| DeltaTable.vacuum(hours) | Delete unreferenced old files |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is Delta Lake?Fresher+
Q2How do you upsert with PySpark and Delta?1–3 yrs+
Q3How does time travel work?1–3 yrs+
Q4Why do Delta tables get slow over time, and what do you do?3+ yrs+
Key takeaways
- ✓Delta works from plain PySpark with one pip package.
- ✓MERGE, history and time travel make data changes safe and auditable.
- ✓Schema enforcement stopped a bad append; mergeSchema allowed the real change.
- ✓Compact small files regularly.
Frequently asked questions
Do I need Databricks to use Delta Lake?
No. Delta Lake is open source. pip install delta-spark and configure your SparkSession, as in this lesson. Databricks adds extras (liquid clustering, predictive optimization, Unity Catalog), but the core table format works anywhere Spark runs.
What's in the _delta_log folder?
One JSON file per commit (00000000000000000000.json, ...0001.json...) listing which data files were added or removed, plus schema and metadata changes, and periodic Parquet checkpoints. The current table is whatever the log says.
Which delta-spark version do I need?
Match it to your Spark version: delta-spark 4.0.x for Spark 4.0, 3.x for Spark 3.5. The configure_spark_with_delta_pip helper downloads the matching jars the first time.
Is Delta the same as Iceberg?
Both are open table formats that add ACID transactions, time travel and schema evolution on top of Parquet files. Delta is native to Databricks; Iceberg is popular with Snowflake, AWS and Trino. The ideas transfer directly.
🧠 Quick check: Delta Lake
1. After MERGE, what did DESCRIBE HISTORY show?
2. Reading versionAsOf 0 gave order 100002 status...
3. Appending a DataFrame with an extra column by default...
4. OPTIMIZE did what in our run?
Checking your access…