# 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.
2. Explain Like I'm 5
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 TraceReferential Integrity & CASCADE Engine
DELETE FROM departments WHERE id = 1; -- Trigger CASCADE to employeesActive InputStep 1: Check Parent Record
Status: Pending Delete
Status: Active
The database acquires a row-level Exclusive Lock on department 1 (IT).
4. Real-World Example
We have two tables: Departments and Employees.
| id (PK) | name |
|---|---|
| 1 | IT |
| 2 | HR |
| id (PK) | name | department_id (FK) |
|---|---|---|
| 101 | Lucky | 1 |
| 102 | Rahul | 2 |
| 103 | Amit | 1 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectCREATE TABLE departments ( id INT PRIMARY KEY, name VARCHAR(100) );
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100), department_id INT, FOREIGN KEY (department_id) REFERENCES departments(id) );
INSERT INTO departments VALUES (1, 'IT'), (2, 'HR'); INSERT INTO employees VALUES (101, 'Lucky', 1), (102, 'Rahul', 2);
-- Fails with constraint violation! INSERT INTO employees VALUES (103, 'Amit', 99); -- ERROR: insert on table "employees" violates foreign key constraint
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Duplicate values | Allowed (multiple employees can reference the same department). |
| NULL values | Allowed unless NOT NULL constraint is explicitly specified. |
| Multiple foreign keys | Allowed in one table (e.g. orders can reference users, coupons, and warehouses). |
| Referenced value | Must exist in the parent table (unless the foreign key column is NULL). |
| Delete parent | May 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;
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 Key | Foreign Key |
|---|---|
| Uniquely identifies a row | References a key in another table |
| Cannot be NULL | Can be NULL |
| Must be unique | Can have duplicates |
| One PK per table | Multiple 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
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?