1.PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL and CHECK Constraints
PRIMARY KEY uniquely identifies a row and forbids NULL. FOREIGN KEY requires a value to reference an existing row elsewhere. UNIQUE forbids duplicate values (NULLs excepted). NOT NULL forbids a missing value. CHECK enforces an arbitrary boolean condition on a row. Each rejects a bad write outright rather than allowing it.
Key features
- PRIMARY KEY = UNIQUE + NOT NULL, plus marking the column as the table's canonical identifier — a table can have only one
- FOREIGN KEY requires the referenced column to be UNIQUE or PRIMARY KEY on the other table, and rejects a value with no matching row
- UNIQUE allows multiple NULLs by default — NULL is never considered equal to another NULL, so two NULLs do not violate uniqueness
- CHECK enforces any boolean expression evaluated per row, e.g. CHECK (price >= 0)
- Every constraint is enforced at write time (INSERT/UPDATE) — a violating row is rejected, the transaction sees an error, nothing bad is ever stored
What each constraint actually rejects
- PRIMARY KEY — unique + not null identifier
- FOREIGN KEY — must reference a real row
- UNIQUE — no duplicate non-NULL values
- NOT NULL — must be present
- CHECK (expr) — arbitrary boolean rule
Command
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INT NOT NULL REFERENCES customers(id),
order_number TEXT UNIQUE NOT NULL,
total NUMERIC NOT NULL CHECK (total >= 0)
);PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL and CHECK each enforce a different invariant, and all are checked on every write from any code path — application-level validation only protects the one path it was written for.