0PricingLogin
SQL Academy · Lesson

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

  1. NOT NULL and CHECK Constraints
  2. UNIQUE Constraints and Composite Keys
  3. FOREIGN KEY and Referential Actions
  4. DEFAULT Values and Generated Columns
← Back to SQL Academy