Sub topic 11
Schema enforcement and schema evolution
This chapter assumes you can write basic SQL and PySpark, and that you have created a Delta table in a Unity Catalog schema such as main.sales. You should also know that a Delta table stores its schema in the transaction log.
Schema enforcement
Delta Lake checks every write against the table schema. This check is called schema enforcement. If the incoming data does not fit, the write fails and the table does not change. No partial data is committed, because the failed write never produces a new table version.
A write is rejected when any of these is true:
- The data has a column that the table does not have.
- A column's type cannot be safely converted to the table's type.
- A column with a
NOT NULLconstraint receives a null. - A
CHECKconstraint evaluates to false for any row.
Enforcement protects downstream readers. A typo such as cutomer_id fails loudly instead of silently creating a new column.
Schema evolution
Sometimes the schema should change. Schema evolution lets a write update the table schema as part of the same commit. You have to ask for it explicitly, so changes are never accidental.
Evolving with a DataFrame write
Set the mergeSchema option to true on the write.
(new_df.write
.format("delta")
.mode("append")
.option("mergeSchema", "true")
.saveAsTable("main.sales.orders"))Columns that exist in new_df but not in the table are added to the end of the table schema. Rows already in the table get NULL for the new column. Columns that exist in the table but not in new_df are filled with NULL in the new rows. They must therefore be nullable.
Evolving with MERGE
For MERGE, schema evolution is off by default. The UPDATE SET * and INSERT * clauses only work when the source columns match columns in the target. You can turn on automatic evolution for the session.
SET spark.databricks.delta.schema.autoMerge.enabled = true;
MERGE INTO main.sales.orders AS t
USING main.sales.orders_updates AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;With this setting, new source columns are added to the target. Without it, the merge fails if the source has extra columns.
Changing the schema directly
You can also change the schema with ALTER TABLE, independent of any write.
ALTER TABLE main.sales.orders ADD COLUMNS (channel STRING);Adding columns is cheap, because it only changes metadata in the log. Renaming or dropping columns needs column mapping to be enabled on the table. Without it, those operations are rejected.
Overwrites and schema changes
A plain overwrite still enforces the schema. To replace the table schema along with the data, use the overwriteSchema option together with mode("overwrite"). This rewrites the whole table, so use it with care. Because the old version stays in the history, you can still undo it with RESTORE while the files remain.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `A schema mismatch detected when writing to the Delta table` | The DataFrame has extra columns | Add `mergeSchema`, or drop the columns |
| `Failed to merge incompatible data types` | A column type differs, for example `STRING` vs `BIGINT` | Cast the column in the DataFrame |
| `MERGE` fails on new source columns | Auto-merge is off | Set `autoMerge.enabled`, or add the column first with `ALTER TABLE` |
| Null written to a required column | `NOT NULL` constraint | Clean the data before the write |
Exercise
A job appends a DataFrame with an extra column channel to main.sales.orders and fails with a schema mismatch error. Give two ways to fix this, and say what existing rows contain for channel afterwards.
Show answer
Either add .option("mergeSchema", "true") to the write, or run ALTER TABLE main.sales.orders ADD COLUMNS (channel STRING) before the append. Existing rows have NULL in the new channel column.
Exercise
Why does a failed schema-enforcement check leave the table unchanged?
Show answer
The write is one atomic commit to the transaction log. When validation fails, no new log entry is written, so no new table version exists and readers see only the previous version.