Sub topic 6
Defining Schemas and Constraints
This chapter assumes you can create a Delta table with SQL (covered in the earlier chapter on CREATE TABLE and CTAS), and that you know basic SQL data types. Here you will learn how to make a table reject bad data instead of storing it.
Why define a schema up front
A Delta table stores its schema in the transaction log. Every write is checked against that schema. If you define the schema explicitly, you decide what the table accepts. If you let CTAS infer it, the schema reflects whatever the query returned, which may be looser than you want.
Two tools tighten the contract beyond column names and types:
NOT NULLsays a column must always have a value.CHECKsays a Boolean expression must be true for every row.
Both are enforced on write. A write that violates either one fails, and the table does not change.
Declaring column types and NOT NULL
Choose types that match the data. Use DECIMAL(10,2) for money, not DOUBLE, because decimals do not accumulate rounding error. Use TIMESTAMP for event times and DATE for calendar days.
CREATE TABLE IF NOT EXISTS main.sales.orders (
order_id BIGINT NOT NULL,
customer_id BIGINT,
order_ts TIMESTAMP,
amount DECIMAL(10,2),
status STRING
) USING DELTA;Here order_id cannot be null. The other columns are nullable, which is the default. Inserting a row without an order_id fails with an error, and no partial data is written.
Adding CHECK constraints
A CHECK constraint has a name and a condition. You can add one to an existing table:
ALTER TABLE main.sales.orders
ADD CONSTRAINT positive_amount CHECK (amount >= 0);When you run this, Delta first validates the rows already in the table. If any existing row breaks the rule, the ALTER TABLE fails and no constraint is added. Fix or delete the offending rows, then try again.
After the constraint exists, every INSERT, UPDATE, and MERGE is tested against it. Note how SQL treats nulls: if amount is null, amount >= 0 evaluates to null, not false, and a null result passes a CHECK. Combine CHECK with NOT NULL when you need both.
To remove a constraint, use ALTER TABLE ... DROP CONSTRAINT positive_amount. To change the rule, drop it and add a new one.
How enforcement works
Because the check happens before the commit, a failed write leaves no half-written state. This relies on the atomic commit described in the transaction log chapter.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `DELTA_NOT_NULL_CONSTRAINT_VIOLATED` | A row has a null in a `NOT NULL` column | Clean the source data or use `COALESCE` |
| `DELTA_VIOLATE_CONSTRAINT_WITH_VALUES` | A row failed a `CHECK` | Filter or correct the row before writing |
| `ALTER TABLE ADD CONSTRAINT` fails | Existing rows already break the rule | Query for violators with the opposite condition, then fix them |
| A `CHECK` seems to allow bad rows | The column is null, and null passes | Add `NOT NULL` or write `col IS NOT NULL AND ...` |
To find rows that would break a new rule, query for the opposite condition:
SELECT * FROM main.sales.orders
WHERE amount < 0 OR amount IS NULL;Check your understanding
Exercise
A table has a column quantity INT with the constraint CHECK (quantity > 0). You insert a row where quantity is null. Does the insert succeed, and what would you add so it fails?
Show answer
The insert succeeds, because NULL > 0 evaluates to null and a null result does not fail a CHECK. Declare the column NOT NULL (or add ALTER TABLE ... ALTER COLUMN quantity SET NOT NULL) so null values are rejected.
Exercise
You run ALTER TABLE main.sales.orders ADD CONSTRAINT positive_amount CHECK (amount >= 0) and it fails. The table was not changed. What is the most likely reason, and how do you find the cause?
Show answer
Existing rows already violate the rule. Run SELECT * FROM main.sales.orders WHERE amount < 0 to find them, correct or delete those rows, and run the ALTER TABLE again.