Module F-6·20 min read

PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK — letting the database enforce your rules so application code does not have to.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

F-6 — Constraints and Data Integrity

Who this module is for: You completed F-5 and can query data across multiple tables. Now you need to understand how to make the database enforce your rules automatically — so bad data cannot enter even if your application has a bug. Constraints are the database's immune system.


Why Constraints Matter

Imagine a bug in your application that accidentally submits an order with customer_id = 999 — but no customer with ID 999 exists. Without constraints, PostgreSQL happily stores this invalid order. Your data becomes inconsistent: you have orders that reference customers who do not exist.

Or your application has a bug that allows two users to register with the same email address. Now you have duplicate accounts and authentication breaks.

Constraints prevent these problems at the database level — not in your application code, not in your API layer, but at the very last line of defence before data is written to disk.


PRIMARY KEY — Every Row Needs a Unique Identity

A primary key uniquely identifies each row. No two rows can have the same primary key value, and it can never be NULL.

sql

When you insert a row that violates the primary key:

sql

BIGSERIAL vs manual ID: when you use BIGSERIAL, PostgreSQL automatically assigns the next available integer. You never specify id in your INSERT — it is generated for you. This is the correct pattern for most tables.


NOT NULL — Mandatory Fields

NOT NULL prevents a column from ever being left empty.

sql

Rule: if a column must always have a value, add NOT NULL. If the value is sometimes unknown or optional, leave the column nullable. Be intentional — a column without NOT NULL silently accepts missing data.


UNIQUE — No Duplicates Allowed

UNIQUE ensures no two rows have the same value in that column (or combination of columns).

sql

When a unique constraint is violated:

sql

UNIQUE vs PRIMARY KEY:

  • PRIMARY KEY = unique + not null + the table's main identifier (one per table)
  • UNIQUE = no duplicates, but NULLs are allowed (and multiple NULLs count as different values in PostgreSQL)

FOREIGN KEY — Referential Integrity

A foreign key ensures that a value in one table references a real row in another table. It is the constraint that makes joins meaningful.

sql

What happens when you delete a referenced row?

By default, trying to delete a customer who has orders fails:

sql

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.