Lesson 13: Constraints: PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL

14 Jul 2026 1 min Swarnil Singhai

Constraints let the database itself enforce data integrity rules — invalid data is rejected at write time, not discovered later in a bug report.

Real-time example

An email field being UNIQUE stops two customer accounts from ever sharing the same email, no matter what the application code does.

CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    email VARCHAR(100) UNIQUE NOT NULL,
    referred_by INT REFERENCES customers(id)
);

What's happening

Because the constraint lives in the database, it protects data integrity even from a buggy script or a rogue direct SQL command.

Push correctness rules into constraints wherever possible — application-level validation alone can always be bypassed.

Advertisement