Constraints and generated columns
A negative amount or a missing customer id breaks every report built on a table. Constraints put the rules on the table itself, so every writer is checked, whatever tool it uses. This lesson shows NOT NULL and CHECK constraints, generated columns and identity columns in Delta.
Step 3 · Data lake & lakehouse · Silver · Delta day to day, lesson 4 of 4
On this page
Show code in
Every code block on the page follows this.
Read first: Schema enforcement and evolution · The Delta transaction log (skip if you know them)
In plain words first
A shop till that will not accept a negative price protects every cashier at once, instead of trusting each one to remember the rule. A constraint is that rule built into the table: any write that breaks it fails as a whole, so bad rows never land.
Why constraints
A pipeline that writes a negative amount or a null customer id produces wrong numbers for every report built on it. Validating in each job is easy to forget. A constraint lives with the table, so every writer (Spark, SQL, streaming, another team) is checked the same way, and the failing write is rejected atomically: none of its rows are committed.
NOT NULL and CHECK
spark.sql(""" CREATE TABLE sales.orders ( order_id BIGINT NOT NULL, customer_id BIGINT NOT NULL, amount DECIMAL(12,2), status STRING, order_ts TIMESTAMP ) USING delta """) spark.sql(""" ALTER TABLE sales.orders ADD CONSTRAINT amount_non_negative CHECK (amount >= 0) """) spark.sql(""" ALTER TABLE sales.orders ADD CONSTRAINT valid_status CHECK (status IN ('placed', 'shipped', 'delivered', 'cancelled')) """)
CREATE TABLE sales.orders ( order_id BIGINT NOT NULL, customer_id BIGINT NOT NULL, amount DECIMAL(12,2), status STRING, order_ts TIMESTAMP ) USING delta; ALTER TABLE sales.orders ADD CONSTRAINT amount_non_negative CHECK (amount >= 0); ALTER TABLE sales.orders ADD CONSTRAINT valid_status CHECK (status IN ('placed', 'shipped', 'delivered', 'cancelled'));
Step 1 · the batch
amount = -50.Step 2 · the check
Step 3 · rejected
DELTA_VIOLATE_CONSTRAINT_WITH_VALUES, naming the constraint and the bad value. Nothing is committed: the other 9,999 rows are not written either.Step 4 · handle it
- Adding a CHECK constraint to an existing table validates all existing rows first, and fails if any violate it.
- Constraints are stored in the table properties and in the transaction logtransaction log: The ordered list of commits that defines which files make up a Delta table at each version. Learn more → protocol: old readers that do not understand them may be blocked from writing.
ALTER TABLE ... DROP CONSTRAINT nameremoves one.- Delta does not enforce primary or foreign keys; on Databricks they are informational only. Uniqueness must be ensured by MERGE logic.
Generated columns
A generated column is computed from other columns on every write. You cannot write a different value into it.
from delta.tables import DeltaTable (DeltaTable.create(spark).tableName("events") .addColumn("event_id", "BIGINT") .addColumn("event_ts", "TIMESTAMP") .addColumn("event_date", "DATE", generatedAlwaysAs="CAST(event_ts AS DATE)") .partitionedBy("event_date") .execute())
CREATE TABLE events ( event_id BIGINT, event_ts TIMESTAMP, event_date DATE GENERATED ALWAYS AS (CAST(event_ts AS DATE)) ) USING delta PARTITIONED BY (event_date);
The bonus: a query that filters only on event_ts still gets partition pruning, because Delta knows how event_date is derived and adds the matching partition filter. Writers no longer need to remember to fill event_date correctly.
Identity columns
spark.sql(""" CREATE TABLE dim_customer ( customer_sk BIGINT GENERATED ALWAYS AS IDENTITY, customer_id STRING, name STRING ) USING delta """)
CREATE TABLE dim_customer ( customer_sk BIGINT GENERATED ALWAYS AS IDENTITY, customer_id STRING, name STRING ) USING delta;
Values are unique and increasing, but not consecutive: each writer tasktask: The work for one partition in one stage, run on one CPU core. Learn more → reserves its own range, so gaps are normal. Identity columns make concurrent writes harder (writers must coordinate the high-water mark), and Delta disables some concurrent-write optimisations for such tables.
In Iceberg
Iceberg tables support required (NOT NULL) fields and, in format v3, default values; CHECK constraints are not part of the spec, so value checks live in the pipeline or engine. Iceberg's hidden partitioning gives the benefit of generated partition columnspartition column: The column a table is split into folders by, such as one folder per date. Learn more → without any extra column: partition by days(event_ts) and filters on event_ts prune automatically.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session with Delta Lake, with spark already created: each builds its own data.
Goal: Make the table reject bad rows itself, and compute a column automatically.
import os, re path = os.path.abspath("lab/constraints/payments") spark.sql(f"""CREATE OR REPLACE TABLE delta.`{path}` ( id BIGINT NOT NULL, amount DOUBLE, paid_at TIMESTAMP, paid_date DATE GENERATED ALWAYS AS (CAST(paid_at AS DATE)) ) USING delta""") spark.sql(f"ALTER TABLE delta.`{path}` ADD CONSTRAINT positive CHECK (amount > 0)") insert = f"INSERT INTO delta.`{path}` (id, amount, paid_at) VALUES " spark.sql(insert + "(1, 50.0, TIMESTAMP'2025-03-01 10:15:00')") for label, values in [("negative amount", "(2, -5.0, TIMESTAMP'2025-03-01 11:00:00')"), ("null id", "(NULL, 5.0, TIMESTAMP'2025-03-01 11:00:00')")]: try: spark.sql(insert + values) except Exception as e: print(f"{label}: rejected,", re.search(r"\[(\w+)\]", str(e)).group(0)) spark.read.format("delta").load(path).show() # paid_date was computed by Delta
Output from a real run
negative amount: rejected, [DELTA_VIOLATE_CONSTRAINT_WITH_VALUES] null id: rejected, [DELTA_NOT_NULL_CONSTRAINT_VIOLATED] +---+------+-------------------+----------+ | id|amount| paid_at| paid_date| +---+------+-------------------+----------+ | 1| 50.0|2025-03-01 10:15:00|2025-03-01| +---+------+-------------------+----------+
What to notice:
- The negative amount broke the
CHECKand the null id brokeNOT NULL: both inserts were rejected. - Only the valid payment is in the table.
paid_datewas never inserted: Delta computed it frompaid_at.
Common mistakes
- Relying on constraints as the only validation — One bad row fails the whole write. Filter and quarantine first; let the constraint catch what slips through.
- Expecting primary keys to be enforced — Delta does not enforce uniqueness. Use MERGE and dedup.
- Expecting identity values without gaps — They are unique, not consecutive.
- Adding a CHECK to a table with existing bad rows — The ALTER fails; clean the data first.
Key takeaways
- Constraints validate values on every write; violations fail the whole write.
- Primary and foreign keys are not enforced.
- Generated columns derive values and enable pruning on the source column.
- Identity columns are unique but have gaps.
Interview prep
THE QUESTION
"How do you stop bad records from reaching a Delta table that several teams write to?"
Avoid: "validate in each pipeline". Code checks can be skipped by a new writer; table constraints cannot.
Follow-ups · answer out loud, then open
Follow-up"What happens to existing data when you add a CHECK constraint?"
Scenario"You want a column that is always the date part of event_ts, without trusting writers to fill it."
event_date DATE GENERATED ALWAYS AS (CAST(event_ts AS DATE)). Delta computes it on write and rejects inconsistent values; if you partition by it, filters on event_ts can also prune partitions.Trap"A PRIMARY KEY constraint on a lakehouse table prevents duplicate keys."
Check yourself
3 questionsA batch of 1,000 rows has one row violating a CHECK constraint. What is written?
Show the answer
Nothing. The write fails atomically.
Why does a generated event_date column help queries filtering on event_ts?
Show the answer
Delta derives a partition filter from the generation expression. Knowing event_date = CAST(event_ts AS DATE) lets Delta prune partitions.
Identity column values are...
Show the answer
Unique and increasing, possibly with gaps. Writers reserve ranges, so gaps are normal.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Changing data · 7 min readMERGE INTO and upserts
Matched, not-matched and not-matched-by-source clauses, step by step, and the duplicate-source error.
Related lessons
Schema enforcement and evolutionData lake & lakehouse · 6 min read
Hidden partitioning and partition evolution
Previous: Schema enforcement and evolution
Primary sources: Delta constraints · Delta generated columns