Delta Lake MERGE, Time Travel and Restore in PySpark: Hands-On
MERGE and time travel are the two Delta features you will use most at work: one to load changes, the other to fix mistakes. Here is working PySpark for both, and what each step writes to the transaction log.
MERGE: update and insert in one step
from delta.tables import DeltaTable
t = DeltaTable.forPath(spark, "/data/outputs/orders_merge")
(t.alias("t")
.merge(updates.alias("u"), "t.order_id = u.order_id")
.whenMatchedUpdateAll()
.whenNotMatchedInsertAll()
.execute())In the Spark Lab lesson **D4**, the table has 1,000 rows and the updates have 1,500: 1,000 match and are updated, 500 are new. The commit is one MERGE with numTargetRowsUpdated 1000 and numTargetRowsInserted 500.
Time travel: read an older version
spark.read.format("delta").option("versionAsOf", 0).load(path).count()
# or by time
spark.read.format("delta").option("timestampAsOf", "2026-11-28 10:00:00").load(path)Restore: undo a bad change
DeltaTable.forPath(spark, path).restoreToVersion(0)Restore does not delete history. It adds a new commit (RESTORE) that brings back the files of version 0, so you can still read the bad version later.
Try it
Open the Spark Lab, run **D3** and **D4**, and watch the Delta log panel. Click **Read vN** on any commit to insert the time-travel code for that version.
Common mistakes
- Two source rows matching one target row: MERGE fails. Deduplicate the updates first.
- Reading a version after VACUUM removed its files: time travel only works while the files exist (7 days by default).
Also try
How to use the Spark Lab: step by step
- Start the Spark Lab and connect
- Run lesson D3 (time travel) and D4 (MERGE)
- Open the Delta log panel
- Click Read vN to try another version
When to use the Spark Lab
- Loading daily changes into a table
- Fixing a bad write without a backup
- Auditing what changed between two versions
- Practising for Databricks certification
Frequently asked questions
Do I need Databricks to learn Delta Lake?
No. Delta Lake is open source. The Spark Lab runs Spark with Delta Lake on your own computer in Docker, free, with no account.
Which Delta Lake version does the lab use?
Delta Lake 3.2 on Apache Spark 3.5, with the jars baked into the lab image so it works offline.
Where are my Delta tables stored?
In /data/outputs inside the lab, which is a Docker volume (datautility-spark-data) on your computer. Nothing is uploaded.
Can I see the _delta_log files?
Yes. The Delta log panel under the editor lists every commit with its operation and row counts, and shows the raw JSON. You can also run docker exec spark-lab ls /data/outputs/<table>/_delta_log.