FOREIGN KEY and Referential Actions
Tie tables together with FOREIGN KEY, and choose ON DELETE CASCADE / SET NULL / RESTRICT for the right behaviour.
What a Foreign Key Does
A FOREIGN KEY makes the database refuse rows that point to non-existent parents:
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
total NUMERIC(10,2) NOT NULL
);
-- Inserting an order with user_id=999 fails if no such user exists.Why Use Foreign Keys?
FKs enforce referential integrity:
- No orphan rows
- Catches application bugs at insert time
- Makes ER diagrams accurate
- Powers automatic cascade behaviour
All lessons in this course
- NOT NULL and CHECK Constraints
- UNIQUE Constraints and Composite Keys
- FOREIGN KEY and Referential Actions
- DEFAULT Values and Generated Columns