SQL · Module 7 · Lesson 12 min read

Relationships, Primary & Foreign Keys

Why split data into several tables?

If every expense row stored the user's name, email and city, then changing an email would mean updating hundreds of rows (and missing one creates inconsistent data). Instead we store each fact once and link tables with keys.

Primary key (PK)

Uniquely identifies each row in its own table: users.id

Foreign key (FK)

A column that points to a primary key in another table: expenses.user_id → users.id

  • The database guarantees the referenced row exists (referential integrity)
  • You can't add an expense for user 999 if there's no user 999

The 3 types of relationships

One-to-many (1:N) — the most common

One user → many expenses. The FK lives on the "many" side (expenses.user_id).

One-to-one (1:1)

One user → one profile. FK with a UNIQUE constraint: profiles.user_id INT UNIQUE REFERENCES users(id). Often used to split rarely used or sensitive columns.

Many-to-many (M:N)

Students ↔ courses, expenses ↔ shared users, posts ↔ tags. You need a junction table (also called a join/bridge table) with two FKs: enrollments(student_id, course_id, PRIMARY KEY (student_id, course_id))

Self-referencing

A table that points to itself: users.referred_by → users.id, categories.parent_id → categories.id (trees and hierarchies)

ON DELETE / ON UPDATE actions

What happens to child rows when the parent is deleted?

ActionEffect
NO ACTION / RESTRICT (default)block the delete
CASCADEdelete the children too
SET NULLset the FK to NULL
SET DEFAULTset the FK to its default

Choose deliberately: expenses → CASCADE with the user; category → SET NULL (keep the expense, lose the category); order → RESTRICT (never silently delete invoices).

Index your foreign keys

PostgreSQL does not automatically index FK columns. Add an index on expenses(user_id) for fast joins and fast deletes (Unit 11).

Example

SQL
-- One-to-many: already in the practice DB (users 1 → N expenses)
SELECT conname, pg_get_constraintdef(oid)
FROM pg_constraint
WHERE conrelid = 'expenses'::regclass AND contype = 'f';
-- expenses_user_id_fkey     | FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-- expenses_category_id_fkey | FOREIGN KEY (category_id) REFERENCES categories(id)

-- ❌ Referential integrity: user 999 doesn't exist
-- INSERT INTO expenses (user_id, title, amount) VALUES (999, 'Ghost', 100);
-- ERROR: insert or update on table "expenses" violates foreign key constraint

-- One-to-one: a profile per user
CREATE TABLE profiles (
  user_id   INT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,  -- PK + FK = 1:1
  bio       TEXT,
  avatar_url TEXT
);

-- Many-to-many: shared expenses (split a bill between friends)
CREATE TABLE expense_splits (
  expense_id BIGINT REFERENCES expenses(id) ON DELETE CASCADE,
  user_id    INT    REFERENCES users(id)    ON DELETE CASCADE,
  share      NUMERIC(10,2) NOT NULL CHECK (share > 0),
  PRIMARY KEY (expense_id, user_id)
);
INSERT INTO expense_splits VALUES (2, 1, 600), (2, 2, 600), (2, 3, 600);  -- Dinner at Thamel ÷ 3

-- ON DELETE SET NULL: keep expenses if a category is removed
ALTER TABLE expenses DROP CONSTRAINT expenses_category_id_fkey;
ALTER TABLE expenses ADD CONSTRAINT expenses_category_id_fkey
  FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL;

DELETE FROM categories WHERE name = 'Entertainment';
SELECT title, category_id FROM expenses WHERE title IN ('Concert', 'Paragliding');
-- both still exist, category_id is now NULL

-- Index the FK columns used in joins
CREATE INDEX idx_expenses_user_id ON expenses(user_id);