Lesson 226 of 296
Constraints
What you will learn
- Why constraints belong in the database
- NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT
- Foreign key actions: CASCADE, RESTRICT, SET NULL
- Exclusion constraints
- Handling constraint errors in an API
On this page
Why constraints?
Application validation (Zod, class-validator) can be bypassed: a bug, a script, a second service, a manual fix in production, or two requests at the same moment. Constraints are rules enforced by the database itself, so invalid data cannot be saved, whatever path it took. They are the last line of defence for data integrity, and some rules (uniqueness under concurrency) can only be enforced reliably by the database.
The constraints, tested
Each of these was run against the sample database, and each was refused:
| Constraint | Statement | PostgreSQL error |
|---|---|---|
| UNIQUE | Insert a customer with aisha@example.com again | duplicate key value violates unique constraint "customers_email_key" |
| FOREIGN KEY | Insert an order for customer 99, who does not exist | insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey" |
| CHECK | Insert an order with status 'shipped' | new row for relation "orders" violates check constraint "orders_status_check" |
| CHECK | Insert a product with price 0 | new row for relation "products" violates check constraint "products_price_pence_check" |
| NOT NULL | Insert a customer with no name | null value in column "name" of relation "customers" violates not-null constraint |
| Constraint | Guarantees |
|---|---|
NOT NULL | A value must be present |
UNIQUE | No two rows share the value (or combination: UNIQUE (tenant_id, email)) |
PRIMARY KEY | NOT NULL + UNIQUE; identifies the row |
FOREIGN KEY ... REFERENCES | The value exists in the referenced table |
CHECK (condition) | Any rule on the row: quantity > 0, end_date > start_date, status IN (...) |
DEFAULT value | Not a rule, but fills a value when none is given: created_at timestamptz NOT NULL DEFAULT now() |
Name your constraints (CONSTRAINT orders_quantity_positive CHECK (quantity > 0)) so error messages and migrations are clear.
Foreign key actions
What happens to orders when their customer is deleted?
| Action | Effect |
|---|---|
ON DELETE RESTRICT / NO ACTION (default) | Refuse the delete while orders exist (we saw this in Lesson 214) |
ON DELETE CASCADE | Delete the orders too (and their items, if they cascade) |
ON DELETE SET NULL | Keep the orders, set customer_id to NULL (the column must allow NULL) |
ON DELETE SET DEFAULT | Set it to the column default |
Use CASCADE for things that truly belong to the parent and mean nothing alone (order items of an order). Use RESTRICT for important history (orders of a customer): deleting a customer should be a deliberate process, often a soft delete or anonymisation (Lesson 228) because of accounting and legal rules.
Exclusion constraints
"No two bookings for the same room may overlap in time" cannot be written as UNIQUE. PostgreSQL's exclusion constraint handles it:
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_bookings (
room_id integer NOT NULL,
during tstzrange NOT NULL,
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);&& means "overlaps". Two concurrent requests trying to book overlapping times: the database lets only one succeed. Very useful in booking-system design (Lesson 243).
Handling constraint errors in an API
Do not check-then-insert in code ("does this email exist? no? insert"): two requests can both pass the check. Insert, and handle the constraint error:
| PostgreSQL error code | Meaning | HTTP response |
|---|---|---|
23505 unique_violation | Duplicate | 409 Conflict ("Email already registered") |
23503 foreign_key_violation | Referenced row missing (or still referenced on delete) | 422 or 409 |
23514 check_violation | Rule broken | 422 |
23502 not_null_violation | Missing value | 422 (usually caught by validation first) |
Map these in one place (an error filter in NestJS, Lesson 209). Prisma reports unique violations as error code P2002.
How to say it in an interview
"Constraints enforce data integrity in the database, so no bug, script or race can save invalid data; uniqueness under concurrency can only be guaranteed there. I use NOT NULL, UNIQUE including composite ones scoped by tenant, primary and foreign keys, and CHECK constraints for rules like positive quantities or allowed statuses, with named constraints. Foreign key actions decide what happens on delete: CASCADE for owned children like order items, RESTRICT for important history. Exclusion constraints prevent overlapping bookings. Rather than check-then-insert, I insert and map constraint errors such as 23505 to a 409."
Key words
| Word | Meaning |
|---|---|
| Constraint | A rule enforced by the database |
| Data integrity | Data being correct and consistent |
| CHECK | A custom condition every row must meet |
| ON DELETE CASCADE / RESTRICT | Delete children too / refuse the delete |
| Exclusion constraint | Prevents rows that conflict, such as overlapping ranges |
| 23505 | PostgreSQL's unique violation error code |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.