Skip to content
Back to 50 Concepts
Topic 27 of 50foundationsIntermediate

# Topic 27: Foreign Key

Referential integrity, parent-child relationships, ON DELETE CASCADE, ON UPDATE actions, and foreign key indexing requirements.

1. Definition

A Foreign Key is a column (or group of columns) in one table that references a primary key or unique key in another table, maintaining referential integrity between them.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

Imagine a school: Every student belongs to a class. Each class has a unique ID. A student cannot be assigned to a class that doesn't exist. The student's class_id is a Foreign Key.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

Referential Integrity & CASCADE Engine

Step 1 of 3
SQL>DELETE FROM departments WHERE id = 1; -- Trigger CASCADE to employeesActive Input

Step 1: Check Parent Record

Engine Action: Evaluate departments WHERE id = 1
Dept #1 (IT)X-Lock

Status: Pending Delete

Dept #2 (HR)

Status: Active

How the Database Executes This:

The database acquires a row-level Exclusive Lock on department 1 (IT).

💡 Referential integrity check triggers internal FK trigger handler.

4. Real-World Example

We have two tables: Departments and Employees.

Departments
id (PK)name
1IT
2HR
Employees
id (PK)namedepartment_id (FK)
101Lucky1
102Rahul2
103Amit1
Relational walkthrough: Here departments.id is the Primary Key, and employees.department_id is the Foreign Key. The foreign key ensures an employee cannot reference a nonexistent department.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Create Departments table
CREATE TABLE departments (
  id INT PRIMARY KEY,
  name VARCHAR(100)
);
Step 2: Create Employees with Foreign Key constraint
CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(100),
  department_id INT,
  FOREIGN KEY (department_id) REFERENCES departments(id)
);
Step 3: Insert valid records
INSERT INTO departments VALUES (1, 'IT'), (2, 'HR');
INSERT INTO employees VALUES (101, 'Lucky', 1), (102, 'Rahul', 2);
Step 4: Attempt invalid insertion
-- Fails with constraint violation!
INSERT INTO employees VALUES (103, 'Amit', 99);
-- ERROR: insert on table "employees" violates foreign key constraint
Department 99 does not exist, so the foreign key blocks the insertion.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Duplicate valuesAllowed (multiple employees can reference the same department).
NULL valuesAllowed unless NOT NULL constraint is explicitly specified.
Multiple foreign keysAllowed in one table (e.g. orders can reference users, coupons, and warehouses).
Referenced valueMust exist in the parent table (unless the foreign key column is NULL).
Delete parentMay be restricted (NO ACTION / RESTRICT) or trigger an automated cascading action.

7. Deep Dive: ON DELETE CASCADE Mechanics & Indexing

When you configure ON DELETE CASCADE, deleting a parent row automatically purges all child records referencing it. Be careful: CASCADE can delete thousands of related records. Furthermore, in PostgreSQL, foreign keys do NOT automatically create secondary indexes; you must manually index foreign key columns to prevent full table scans and lock contention during parent deletes.

-- Manual index on foreign key column (MANDATORY for production):
CREATE INDEX idx_employees_department_id ON employees(department_id);

-- Cascade configuration:
ALTER TABLE employees
  ADD CONSTRAINT fk_emp_dept
  FOREIGN KEY (department_id) REFERENCES departments(id)
  ON DELETE CASCADE;
Caution: Deleting a parent row without an index on the child table's foreign key triggers a full table scan of the child table and acquires share locks.

8. Advantages & Disadvantages

Advantages

  • •Prevents orphan records and invalid relationships.
  • •Maintains data integrity at the database storage engine layer.
  • •Supports automated lifecycle management via ON DELETE CASCADE / SET NULL.

Disadvantages & Trade-offs

  • •Adds validation overhead during INSERT and UPDATE writes.
  • •Can complicate deletions and cause accidental cascaded data loss.
  • •Requires explicit index creation in PostgreSQL to prevent table lock bottlenecks.

9. Common Interview Questions

Q1.Can a foreign key contain NULL values?

Yes, unless restricted by a NOT NULL constraint. A NULL foreign key represents an optional or unassigned relationship.

Q2.Can a foreign key contain duplicate values?

Yes. Multiple child rows can reference the exact same parent row (e.g. multiple employees in the same department).

Q3.Does a foreign key automatically create an index in PostgreSQL?

No. While primary keys automatically create unique B-Tree indexes, foreign key columns do not. Engineers must create them manually with CREATE INDEX.

Q4.What is the difference between Primary Key and Foreign Key?

A Primary Key uniquely identifies a row in its table and cannot be NULL. A Foreign Key references a key in another table, can contain duplicates, and can be NULL.

Primary KeyForeign Key
Uniquely identifies a rowReferences a key in another table
Cannot be NULLCan be NULL
Must be uniqueCan have duplicates
One PK per tableMultiple FKs per table allowed

10. Interview-Ready Answer

“A foreign key is a constraint that establishes a relationship between two tables and ensures referential integrity. For example, in an employees table, department_id can reference the id column of the departments table, preventing employees from referencing departments that don't exist.”

11. Quick Test

Scenario Question:

We have Users (id 1, 2) and Orders (id 101 for user 1; id 102 for user 2). What happens if we execute "DELETE FROM users WHERE id = 1;" when orders.user_id is a foreign key referencing users.id with default NO ACTION behavior?

Select your answer: