Sub topic 11
Schema enforcement and schema evolution
This chapter assumes you can create a Delta table with SQL, append to it with the DataFrame API, and read the error messages Spark prints in a notebook. It builds on the main.sales.orders table from earlier chapters.
Two sides of the same rule
A Delta table stores its schema in the transaction log. That schema has two jobs:
- Schema enforcement (also called schema validation) rejects writes that do not match the table's schema. The write fails and nothing is committed.
- Schema evolution changes the table's schema so that a write that would have failed can succeed.
Enforcement is the default. Evolution is something you ask for, either per write, per statement, or with an explicit ALTER TABLE. This design keeps a bad upstream change, such as a renamed column, from silently altering a table that other jobs and dashboards depend on.
What enforcement checks
When you write to an existing Delta table, Delta compares the incoming data with the table schema. The main rules are:
| Situation | Default result |
|---|---|
| Incoming data has a column the table does not have | Write fails |
| Incoming data lacks a nullable table column | Write succeeds, and the missing column is filled with NULL |
| Incoming data lacks a `NOT NULL` column, or has NULLs in one | Write fails |
| Incoming column type cannot be safely converted to the table type | Write fails |
| Column names differ only by letter case | Treated as the same column, and the table's casing is kept |
| A `CHECK` constraint evaluates to false for a row | Write fails |
Because a failed write commits nothing, the table stays at its previous version. You do not need to clean up partial files by hand.
Name matching versus position matching
Enforcement depends on how columns are matched. DataFrameWriter operations such as saveAsTable with mode("append") match columns by name. A SQL INSERT INTO ... SELECT matches by position unless you use the BY NAME form. Positional matching is a common source of data landing in the wrong column. If two columns share a type, such as customer_id and order_id, swapping them passes enforcement, because the types are compatible.
-- Positional: the SELECT list must follow the table's column order
INSERT INTO main.sales.orders
SELECT order_id, customer_id, order_ts, amount, status
FROM main.sales.orders_staging;
-- By name: column order in the SELECT does not matter
INSERT INTO main.sales.orders BY NAME
SELECT status, amount, order_ts, customer_id, order_id
FROM main.sales.orders_staging;Write the column list explicitly in production pipelines, even when the order currently matches.
Seeing enforcement fail
Suppose an upstream system starts sending a new channel column. This job appends the data to the table.
from pyspark.sql import Row
new_df = spark.createDataFrame([
Row(order_id=2001, customer_id=7, amount=19.99, status="new", channel="web"),
])
new_df.write.format("delta").mode("append").saveAsTable("main.sales.orders")The write raises an AnalysisException that says a schema mismatch was detected, and it lists the table schema next to the incoming schema. The table is unchanged. You can confirm that with DESCRIBE HISTORY main.sales.orders, which shows no new version.
The error is a signal for you to decide between two actions: fix the producer, or accept the new column.
Evolving the schema on write
Add the mergeSchema option to accept new columns for that one write.
(new_df.write
.format("delta")
.mode("append")
.option("mergeSchema", "true")
.saveAsTable("main.sales.orders"))Delta adds channel as a nullable column at the end of the schema, then writes the rows. Both changes happen in one commit, so readers see either the old schema or the new one, never a mixture. Rows written before this commit read as NULL for channel.
Things to know about mergeSchema:
- New columns are added as nullable. You cannot add a
NOT NULLcolumn this way. - It is not a general type converter. It supports adding columns and a small set of compatible type changes. Changing
amountfromDECIMAL(10,2)toSTRINGstill fails. - It applies to one write. The next write without the option is enforced again.
- For nested
STRUCTcolumns, new fields inside a struct can also be added.
Session-wide evolution
You can switch on automatic merging for a whole session.
spark.conf.set("spark.databricks.delta.schema.autoMerge.enabled", "true")This setting also affects MERGE and some INSERT statements. It is convenient in a notebook but risky in a shared job, because every write in the session can now change table schemas. Prefer the per-write option for DataFrame writes so the intent is visible in the code.
Evolution in MERGE
MERGE with UPDATE SET * or INSERT * enforces the schema too. If the source has extra columns, the merge fails by default. Two ways to allow new columns:
- Turn on
spark.databricks.delta.schema.autoMerge.enabledfor the session. - On recent Databricks Runtime versions, add
WITH SCHEMA EVOLUTIONto the statement.
MERGE WITH SCHEMA EVOLUTION 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 *;Check the Databricks Runtime release notes for your cluster before relying on this syntax. If it is unavailable, use the session setting. In both cases, evolution applies only to columns that SET * or INSERT * carry over. If you list columns explicitly, a source column you did not mention is not added to the target.
Changing the schema deliberately
Evolution on write is reactive. When you already know what the table should look like, change it directly.
-- Add a column
ALTER TABLE main.sales.orders ADD COLUMNS (channel STRING COMMENT 'Sales channel');
-- Rename and drop need column mapping (see the warning below)
ALTER TABLE main.sales.orders SET TBLPROPERTIES ('delta.columnMapping.mode' = 'name');
ALTER TABLE main.sales.orders RENAME COLUMN status TO order_status;
ALTER TABLE main.sales.orders DROP COLUMN channel;Tables in Unity Catalog may already have column mapping enabled, depending on how they were created. If a rename or drop fails, check DESCRIBE DETAIL main.sales.orders and the table properties.
Replacing the schema with overwrite
An overwrite replaces the data but keeps the table schema, so enforcement still applies. To replace the schema as well, use overwriteSchema.
(rebuilt_df.write
.format("delta")
.mode("overwrite")
.option("overwriteSchema", "true")
.saveAsTable("main.sales.orders"))This is a heavy operation. It discards the old schema, and the table history still records every earlier version. Do not combine it with dynamic partition overwrite or a replaceWhere filter. Use it for full rebuilds only.
Choosing an approach
| Goal | Use |
|---|---|
| Reject anything unexpected from an upstream feed | Default enforcement |
| Accept new columns from a trusted source on one job | `mergeSchema` on that write |
| Add a column before any data arrives | `ALTER TABLE ... ADD COLUMNS` |
| Rebuild a table with a different shape | `overwriteSchema` with overwrite |
| Rename or drop columns without rewriting files | Column mapping, then `ALTER TABLE` |
Common errors
- Enabling evolution everywhere. A typo in a producer's column name creates a new column, and the original column goes NULL. Evolution accepts that typo without complaint.
- Assuming extra columns are ignored. They are not. They fail the write unless you select only the columns you want first.
- Positional inserts after a schema change. A new column at the end of the table changes what a bare
INSERT INTO ... SELECT *must supply. - Expecting evolution to relax constraints.
NOT NULLandCHECKconstraints still apply to evolved writes. - Forgetting downstream consumers. Views, jobs and BI tools that use
SELECT *start returning the new column right away.
Exercise
A nightly job appends a DataFrame to main.sales.orders. After an upstream change, the DataFrame has a new column channel, and the job fails with a schema mismatch. The team wants to accept channel for this job only, without changing how other jobs write to the table. What do you change, and what happens to rows that were written before the change?
Show answer
Add .option("mergeSchema", "true") to that job's DataFrameWriter call, and do not set the session-wide autoMerge configuration. Delta adds channel as a nullable column and writes the new rows in one commit. Rows written earlier read as NULL for channel, because their data files do not contain the column. Other jobs that write without the option are still checked against the new schema, and they must either include channel or leave it out, since it is nullable.
Exercise
A colleague runs INSERT INTO main.sales.orders SELECT customer_id, order_id, order_ts, amount, status FROM main.sales.orders_staging. The statement succeeds, yet the data is wrong. Explain why enforcement did not catch it, and give one fix.
Show answer
INSERT INTO ... SELECT matches columns by position. customer_id and order_id are both BIGINT, so the swapped values pass the type check and land in the wrong columns. Fix it by using INSERT INTO ... BY NAME, or by listing the SELECT columns in the table's order. Adding a CHECK constraint on a column's valid range can also catch some swaps.