Skip to content
Silver 6 min read · Delta, Iceberg 2 practice problems ↓

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

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

PySparkSpark SQL · Declaring constraints
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

A batch of 10,000 orders arrives; one has amount = -50.

Step 2 · the check

Delta evaluates every constraint on the rows being written, as part of the write job.

Step 3 · rejected

The write fails with 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

Split the batch yourself first: write rows that pass the same condition, and send the rest to a quarantine table for review. The constraint stays as the last line of defence.
  • 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 name removes 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.

PySparkSpark SQL · Partition by a date derived from a timestamp
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

PySparkSpark SQL · Surrogate keys
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.

Production patternPySpark · NOT NULL, CHECK and a generated column, enforced on every write
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 CHECK and the null id broke NOT NULL: both inserts were rejected.
  • Only the valid payment is in the table.
  • paid_date was never inserted: Delta computed it from paid_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?"

Declare NOT NULL and CHECK constraints on the table, so every writer is validated and violating writes fail atomically. In each pipeline, split records with the same rules and write failures to a quarantine table, so one bad row does not block the batch. Mention schema enforcement for types, that keys are not enforced, and data-quality tools (expectations in Lakeflow / DLT, Great Expectations) for softer checks and metrics.

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?"
Delta validates all existing rows first, and adding the constraint fails if any row violates it. Clean the data, then add the constraint.
Scenario"You want a column that is always the date part of event_ts, without trusting writers to fill it."
Use a generated column: 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."
Primary and foreign keys in Delta (on Databricks) and Iceberg identifier fields are informational: they are not enforced on write. Deduplicate in the pipeline or MERGE by key.

Check yourself

3 questions

A 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 read
MERGE INTO and upserts
Matched, not-matched and not-matched-by-source clauses, step by step, and the duplicate-source error.

Related lessons

Previous: Schema enforcement and evolution

Primary sources: Delta constraints · Delta generated columns