Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PG
PostgreSQL
0/11 completed
Beginner
Why PostgreSQL?psql and your first tablesData types that matter
Intermediate
Constraints and relationshipsPostgres-powered SQLJSONB, arrays and full-text search
Advanced
Views, functions and triggersIndexes and EXPLAINTransactions, MVCC and locking
Pro
Roles, privileges and row-level securityBackups, replication and production
Tracks / PostgreSQL / Intermediate

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

PostgreSQL · editable

Each failure names the exact constraint. Give constraints readable names so errors are self-explanatory:

PostgreSQL · editable

Multi-column rules

A UNIQUE or CHECK can span several columns:

PostgreSQL · editable

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:

PostgreSQL · editable

Foreign keys

A foreign key says "this value must exist in that table". It's how relational databases guarantee relationships stay valid:

PostgreSQL · editable

Customer 999 doesn't exist, so the order is rejected. What about deleting a customer who has orders?

PostgreSQL · editable

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
PostgreSQL · editable

⚠️ CASCADE is powerful: one delete can remove thousands of rows. Use it for data that truly belongs to the parent (a post's likes), and RESTRICT for 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":

PostgreSQL · editable

[ 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

PostgreSQL · editable

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:

  1. members: unique email, name between 2 and 100 characters
  2. books: an isbn that must be exactly 13 characters, copies >= 0
  3. loans: references both tables; deleting a member should be refused if they have loans; due_on must be after borrowed_on

Then try inserting bad data and read each error.

PostgreSQL · editable
✎ Check your understanding

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?

← Data types that matter