Sub topic 3
Upserting with MERGE
Assume you know basic SQL, PySpark DataFrames, Databricks notebooks, and table schemas. This chapter focuses on changing existing Delta tables safely.
Upserting with MERGE
An upsert updates a row when its key exists and inserts it when the key is new. Delta Lake's MERGE statement performs both actions atomically.
The source must contain at most one row for each target key. Duplicate source keys can make the operation fail or produce ambiguous results.
MERGE INTO main.sales.orders AS target
USING main.sales.orders_updates AS source
ON target.order_id = source.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;The * forms require compatible columns. Use explicit column assignments when the source and target have different names or when only selected columns should change.
Schema enforcement and evolution
Schema enforcement rejects incompatible writes, such as a string being written to a numeric column. This protects downstream queries, but a new column also causes a write to fail by default.
Schema evolution allows an intentional compatible change, such as adding a column:
(new_df.write
.format("delta")
.mode("append")
.option("mergeSchema", "true")
.saveAsTable("main.sales.orders"))Use evolution selectively. Automatically accepting renamed or incorrectly typed columns can hide upstream errors.
Table history, time travel, and RESTORE
Each committed change creates a table version in the transaction log. Inspect versions and query an earlier snapshot with:
DESCRIBE HISTORY main.sales.orders;
SELECT *
FROM main.sales.orders VERSION AS OF 3;
RESTORE TABLE main.sales.orders TO VERSION AS OF 3;RESTORE creates a new current version that matches the selected version. It does not erase the history. Time travel is useful for investigation, recovery, and comparing results.
Concurrent writes and conflict handling
Delta Lake checks concurrent transactions before committing. If two operations modify overlapping data or metadata, one may fail with a conflict instead of silently overwriting the other. Retry the failed operation after refreshing its source data. Design jobs to be idempotent, meaning a retry produces the same result.
Keeping tables healthy
OPTIMIZE compacts many small files, improving read performance. VACUUM removes old files no longer needed by the table:
OPTIMIZE main.sales.orders;
VACUUM main.sales.orders RETAIN 168 HOURS;Vacuuming saves storage but can remove files needed for old time-travel versions. Keep the retention period longer than the maximum time-travel or concurrent-reader window.
Exercise
What happens when a source row in MERGE has an existing order_id?
Show answer
The matching target row is updated. A source row with no matching order_id is inserted.