Constraints and relationships
Application code has bugs. Constraints are rules the database enforces on every write, from every app, script and person, so bad data can't get in at all. They're your last line of defence, and they're cheap.
The constraint toolbox
| Constraint | Guarantees |
|---|---|
NOT NULL |
A value is always present |
UNIQUE |
No two rows share this value (or combination) |
PRIMARY KEY |
UNIQUE + NOT NULL: the row's identity |
CHECK (…) |
Any true/false rule you can write |
FOREIGN KEY / REFERENCES |
The value exists in another table |
EXCLUDE |
No two rows "conflict" (such as overlapping time ranges) |
DEFAULT |
Not a rule, but fills in missing values |
CHECK and UNIQUE
Each failure names the exact constraint. Give constraints readable names so errors are self-explanatory:
Multi-column rules
A UNIQUE or CHECK can span several columns:
NULLs and UNIQUE
By default, UNIQUE lets multiple rows have NULL, because SQL treats NULL as "unknown", and two unknowns aren't equal. If you want only one NULL allowed, use NULLS NOT DISTINCT:
Foreign keys
A foreign key says "this value must exist in that table". It's how relational databases guarantee relationships stay valid:
Customer 999 doesn't exist, so the order is rejected. What about deleting a customer who has orders?
Also rejected: deleting would leave "orphan" orders. You decide what should happen with ON DELETE:
| Option | When the parent row is deleted… |
|---|---|
NO ACTION / RESTRICT (default) |
…refuse the delete |
CASCADE |
…delete the child rows too |
SET NULL |
…set the child's foreign key to NULL |
SET DEFAULT |
…set it to the column's default |
⚠️
CASCADEis powerful: one delete can remove thousands of rows. Use it for data that truly belongs to the parent (a post's likes), andRESTRICTfor anything valuable (invoices).
Tip: Postgres automatically indexes primary keys and unique columns, but not foreign-key columns. Add an index on columns like posts.author_id, or deletes and joins get slow on big tables.
Exclusion constraints
UNIQUE stops equal values. An exclusion constraint stops conflicting ones, such as overlapping bookings. tstzrange is a range of timestamps, and && means "overlaps":
[ includes the start and ) excludes the end, so Asha's and Rahul's back-to-back bookings don't overlap. Priya's does, and no amount of race conditions in your app can double-book the room.
Adding constraints to existing tables
Postgres checks existing rows when you add a constraint. On a huge table, ADD CONSTRAINT … NOT VALID followed later by VALIDATE CONSTRAINT avoids a long lock.
Practice
Design a library schema with constraints:
members: unique email, name between 2 and 100 charactersbooks: anisbnthat must be exactly 13 characters,copies >= 0loans: references both tables; deleting a member should be refused if they have loans;due_onmust be afterborrowed_on
Then try inserting bad data and read each error.
1.Why put rules in the database when the app already validates input?
2.A post's comments should disappear when the post is deleted. Which option?
3.Which constraint prevents two meetings in the same room from overlapping in time?