Skip to the content

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:

ConstraintStatementPostgreSQL error
UNIQUEInsert a customer with aisha@example.com againduplicate key value violates unique constraint "customers_email_key"
FOREIGN KEYInsert an order for customer 99, who does not existinsert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
CHECKInsert an order with status 'shipped'new row for relation "orders" violates check constraint "orders_status_check"
CHECKInsert a product with price 0new row for relation "products" violates check constraint "products_price_pence_check"
NOT NULLInsert a customer with no namenull value in column "name" of relation "customers" violates not-null constraint
ConstraintGuarantees
NOT NULLA value must be present
UNIQUENo two rows share the value (or combination: UNIQUE (tenant_id, email))
PRIMARY KEYNOT NULL + UNIQUE; identifies the row
FOREIGN KEY ... REFERENCESThe value exists in the referenced table
CHECK (condition)Any rule on the row: quantity > 0, end_date > start_date, status IN (...)
DEFAULT valueNot 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?

ActionEffect
ON DELETE RESTRICT / NO ACTION (default)Refuse the delete while orders exist (we saw this in Lesson 214)
ON DELETE CASCADEDelete the orders too (and their items, if they cascade)
ON DELETE SET NULLKeep the orders, set customer_id to NULL (the column must allow NULL)
ON DELETE SET DEFAULTSet 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 codeMeaningHTTP response
23505 unique_violationDuplicate409 Conflict ("Email already registered")
23503 foreign_key_violationReferenced row missing (or still referenced on delete)422 or 409
23514 check_violationRule broken422
23502 not_null_violationMissing value422 (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

WordMeaning
ConstraintA rule enforced by the database
Data integrityData being correct and consistent
CHECKA custom condition every row must meet
ON DELETE CASCADE / RESTRICTDelete children too / refuse the delete
Exclusion constraintPrevents rows that conflict, such as overlapping ranges
23505PostgreSQL's unique violation error code

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.