Sub topic 6
Defining Schemas and Constraints
This chapter assumes you can write basic SQL, use PySpark DataFrames, and run cells in a Databricks notebook attached to compute. It also assumes you have seen CREATE TABLE in the previous chapter. Here you will focus on what a Delta table promises about its data: column types, nullability, and rules that every write must satisfy.
Why define a schema up front
A Delta table stores its schema in the transaction log, next to the list of data files. Every write is checked against that schema. If you define the schema deliberately, bad data fails at write time. If you let a tool infer the schema, bad data tends to surface later, in a dashboard or a downstream job.
Delta Lake supports two kinds of rules:
- Structural rules: column names, data types, and whether a column accepts
NULL. - Value rules:
CHECKconstraints, which are boolean expressions that must be true for every row.
Both are enforced by the table, not by the code that writes to it. A notebook, a job, a streaming query, and a SQL warehouse all face the same rules.
Declaring columns and data types
Choose types that match the data, not the types that are easiest to type.
| Data | Recommended type | Notes |
|---|---|---|
| Surrogate or business keys | `BIGINT` | Avoids overflow that `INT` can hit on large tables. |
| Money | `DECIMAL(p,s)` | Exact arithmetic. `DOUBLE` accumulates rounding error. |
| Event times | `TIMESTAMP` | Stored as UTC instants. |
| Calendar dates | `DATE` | Cheaper and clearer than a timestamp at midnight. |
| Free text and codes | `STRING` | No length limit by default. |
DECIMAL(10,2) means 10 digits in total, 2 of them after the decimal point, so the largest value is 99,999,999.99. A value that does not fit raises an error or becomes NULL, depending on whether ANSI mode is on. On current Databricks runtimes ANSI mode is on by default in SQL, so you get an error. Check this on your own compute before relying on it.
You can also attach a comment to each column. Comments appear in Catalog Explorer and help the next person who reads the table.
CREATE TABLE IF NOT EXISTS main.sales.orders (
order_id BIGINT NOT NULL COMMENT 'Unique order identifier',
customer_id BIGINT COMMENT 'Customer that placed the order',
order_ts TIMESTAMP COMMENT 'When the order was placed, UTC',
amount DECIMAL(10,2) COMMENT 'Order total in the account currency',
status STRING COMMENT 'new, shipped or cancelled'
) USING DELTA;NOT NULL constraints
NOT NULL says a column must always have a value. In the table above, order_id is NOT NULL, and every other column accepts NULL.
Delta checks this on every write. An insert that supplies NULL for order_id fails, and the whole statement is rolled back, so no partial rows are committed.
INSERT INTO main.sales.orders (order_id, customer_id, order_ts, amount, status)
VALUES (NULL, 1, current_timestamp(), 10.00, 'new');This statement fails with an error that names the constraint violation. Nothing is written.
You can add or remove NOT NULL on an existing column:
ALTER TABLE main.sales.orders ALTER COLUMN customer_id SET NOT NULL;
ALTER TABLE main.sales.orders ALTER COLUMN customer_id DROP NOT NULL;SET NOT NULL scans the table. If any existing row has NULL in that column, the command fails and the schema stays unchanged. Fix or remove those rows first.
CHECK constraints
A CHECK constraint is a named boolean expression over the columns of one row. Add it with ALTER TABLE:
ALTER TABLE main.sales.orders
ADD CONSTRAINT positive_amount CHECK (amount >= 0);From then on, any INSERT, UPDATE, or MERGE that would produce a row where amount >= 0 is false is rejected. The whole transaction fails.
Three behaviors matter in practice:
- Existing data is validated when you add the constraint. If one row violates it,
ADD CONSTRAINTfails and nothing changes. Query for violators first, for exampleSELECT * FROM main.sales.orders WHERE NOT (amount >= 0). NULLpasses a check. ACHECKfails only when the expression is false. IfamountisNULL, thenamount >= 0evaluates toNULL, and the row is accepted. CombineCHECKwithNOT NULLwhen you need both.- Constraints apply to new writes only after they exist. They do not rewrite files, and they do not protect against writers that bypass Delta, such as someone placing Parquet files directly in the table directory.
You can use several columns and built-in functions in the expression:
ALTER TABLE main.sales.orders
ADD CONSTRAINT valid_status
CHECK (status IN ('new', 'shipped', 'cancelled'));Remove a constraint by name:
ALTER TABLE main.sales.orders DROP CONSTRAINT valid_status;To see the constraints on a table, run DESCRIBE DETAIL main.sales.orders and read the properties column, or SHOW TBLPROPERTIES main.sales.orders. Check constraints appear as properties named delta.constraints.<name>.
Primary and foreign keys in Unity Catalog
Unity Catalog also accepts PRIMARY KEY and FOREIGN KEY declarations. These are informational. Databricks does not enforce them, so duplicate keys are still written. They document relationships and help tools such as query planners and BI products. If you need uniqueness, enforce it in your pipeline, for example with MERGE on the key.
Defining a schema from Python
When you create a table from a DataFrame, supply the schema yourself instead of relying on inference. Inference reads a sample of the data, and one odd value can turn a numeric column into a string.
from pyspark.sql.types import (
StructType, StructField, LongType, TimestampType, DecimalType, StringType
)
schema = StructType([
StructField("order_id", LongType(), nullable=False),
StructField("customer_id", LongType(), nullable=True),
StructField("order_ts", TimestampType(), nullable=True),
StructField("amount", DecimalType(10, 2), nullable=True),
StructField("status", StringType(), nullable=True),
])
(spark.createDataFrame([], schema)
.write.format("delta")
.mode("ignore")
.saveAsTable("main.sales.orders_py"))Using mode("ignore") makes the call a no-op if the table already exists. The nullable=False flag on order_id is carried into the Delta table as NOT NULL. Constraints from CHECK still need ALTER TABLE, which you can run with spark.sql(...).
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ADD CONSTRAINT` fails on an existing table | Some current rows violate the expression | Find them with a `WHERE NOT (...)` query, correct or delete them, then retry. |
| `SET NOT NULL` fails | Existing rows contain `NULL` | Backfill with `UPDATE ... SET col = default WHERE col IS NULL`, then retry. |
| A row with `NULL` passes a `CHECK` | The expression evaluates to `NULL`, not false | Add `NOT NULL` or write `CHECK (col IS NOT NULL AND col >= 0)`. |
| Write fails with a schema mismatch | The incoming DataFrame has different columns or types | Cast and select columns to match, or use schema evolution (covered in a later chapter). |
| Decimal values become `NULL` or error | Value exceeds the declared precision | Widen the type, for example `DECIMAL(12,2)`, or validate upstream. |
Practical guidance
- Put
NOT NULLon keys and on columns your joins depend on. Leave descriptive columns nullable unless you can guarantee a value. - Keep
CHECKexpressions cheap. They run on every row written, so avoid anything that calls external state. They cannot contain subqueries. - Add constraints early. The longer a table runs without them, the more likely it holds rows that block the constraint later.
- Treat a constraint failure as useful information. It means a producer is sending data you did not expect, and the failed write left the table unchanged.
Exercise
The table main.sales.orders has CHECK (amount >= 0) and amount is nullable. A job inserts a row with amount = NULL, and another inserts a row with amount = -5.00. What happens to each insert, and what would you change so the first one is also rejected?
Show answer
The row with amount = NULL is accepted, because NULL >= 0 evaluates to NULL, and a CHECK constraint rejects a row only when its expression is false. The row with amount = -5.00 is rejected and the whole statement fails with no data written. To reject NULL too, run ALTER TABLE main.sales.orders ALTER COLUMN amount SET NOT NULL, which requires that no existing rows have a NULL amount, or replace the constraint with CHECK (amount IS NOT NULL AND amount >= 0).
Exercise
You run ALTER TABLE main.sales.orders ADD CONSTRAINT valid_status CHECK (status IN ('new', 'shipped')) and it fails. The table contains rows with status 'cancelled'. Give two ways to get the constraint added.
Show answer
Either include the missing value in the expression, for example CHECK (status IN ('new', 'shipped', 'cancelled')), or remove the offending rows first with DELETE FROM main.sales.orders WHERE status = 'cancelled' and then add the original constraint. Adding a constraint validates all existing rows, so any violation makes the command fail and leaves the table unchanged.