Constraints ensure data integrity by enforcing rules on columns and tables. Drizzle supports primary keys, foreign keys, unique constraints, and check constraints.
Primary keys
Column-level primary key
The simplest way to define a primary key is on a single column:
Composite primary key
Define a primary key across multiple columns:
Foreign keys
Column-level foreign key
Define a foreign key reference directly on a column:
Foreign key with actions
Specify ON DELETE and ON UPDATE actions:
Available actions:
'cascade' - Delete/update related rows
'restrict' - Prevent delete/update if related rows exist
'no action' - Same as restrict (default)
'set null' - Set foreign key to NULL
'set default' - Set foreign key to default value
Table-level foreign key
Define foreign keys in the table’s extra config:
Composite foreign key
Reference multiple columns:
Named foreign key
Unique constraints
Column-level unique
Mark a single column as unique:
Table-level unique constraint
Define unique constraints on single or multiple columns:
Composite unique constraint
Enforce uniqueness across multiple columns:
NULLS NOT DISTINCT (PostgreSQL)
By default, PostgreSQL considers NULL values as distinct in unique constraints. Use nullsNotDistinct() to treat NULL values as equal:
nullsNotDistinct() is only available in PostgreSQL 15+
Check constraints
Check constraints validate data based on a boolean expression:
Basic check constraint
Multiple column check
Complex check constraint
Check constraints are evaluated for each row. Complex checks can impact performance on large tables.
Complete example