Learn SQL
-- constraints.foreign_key

FOREIGN KEY in SQL

Make relationships real — every child points at a real parent

--concept

A FOREIGN KEY is a column that must contain a value from another table’s primary key (or UNIQUE column). It turns “employees.department should match a department” from a hope into a rule the engine enforces on every write. Orphan rows — children pointing at parents that do not exist — simply become impossible.

--how it works
1

Point the child at the parent

FOREIGN KEY (department) REFERENCES departments(dept_id) — the child column must hold values that exist in the parent’s key.

2

Child writes are validated

INSERT/UPDATE on employees looks the department up in departments: absent parent, rejected child. NULL is allowed — “no department yet” is legal.

3

Parent deletes are guarded

DELETE of a department that still has employees fails by default (RESTRICT/NO ACTION) — referential integrity blocks orphaning.

4

Referential actions automate the choice

ON DELETE SET NULL keeps the children parentless but alive; ON DELETE CASCADE removes them with the parent. Choose deliberately — CASCADE is a loaded weapon.

5

Index the child column

Every parent delete/Update must scan children for references; an index on employees.department turns that scan into a lookup.

--visualization
idnamedepartment1AliceEngineering2BobSales3CynthiaEngineering4DavidMarketing5ElenaSales6FaridEngineeringemployees (child)departments (parent)dept_idlocationEngineeringBerlinSalesMadridMarketingLisbonlookup 'Research'NEW (7, 'Grace', 'Research', 81000, 31)… probing parentscanning departments…
result
Stage 1 / 4
Lesson example: INSERT (7, 'Grace', 'Research', 81000, 31) — but is 'Research' a real department?
--example
query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (7, 'Grace', 'Research', 81000, 31);
Result
error
ERROR: insert or update on table "employees" violates foreign key constraint "employees_department_fkey"Detail: Key (department)=(Research) is not present in table "departments".

There is no Research department, so the engine rejects Grace’s row. To hire into Research you first INSERT the department — the constraint forces the data to stay consistent from day one.

--variants

Real parent — accepted

A child row whose parent exists passes the check.

query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (7, 'Grace', 'Engineering', 81000, 31);
Result
idnamedepartmentsalaryage
7GraceEngineering8100031
1The engine looks up Engineering in departments.dept_id — found.
2The row is written; the relationship is real from birth.
3Every JOIN against departments is now guaranteed to find a match for Grace.

Missing parent — rejected

No Research department exists, so Grace cannot join it.

query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (8, 'Grace', 'Research', 81000, 31);
Result
error
ERROR: insert or update on table "employees" violates foreign key constraint "employees_department_fkey"
1The parent lookup for Research returns nothing.
2The statement fails — an orphan row is impossible by construction.
3Fix the workflow, not the constraint: insert the department first, then the employee.

Deleting a referenced parent

Three declared outcomes: block, null out, or cascade.

query.sql
1DELETE FROM departments WHERE dept_id = 'Sales';
2-- RESTRICT (default): ERROR, 2 employees reference it
3-- ON DELETE SET NULL: employees.department becomes NULL
4-- ON DELETE CASCADE: Bob and Elena are deleted too
Result
errordetail
ERROR: update or delete on table "departments" violates foreign key constraint on "employees"Detail: Key (dept_id)=(Sales) is still referenced from table "employees".
1The engine counts children before removing the parent.
2With the default action the delete is refused — 2 references exist.
3SET NULL / CASCADE change the outcome; the schema declares the policy once, and every query obeys it.

NULL foreign key is legal

A missing value is not a broken relationship.

query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (9, 'Hugo', NULL, 49000, 27);
3-- pending placement — allowed
Result
idnamedepartmentsalaryage
9Hugonull4900027
1NULL means “no parent”, which is a valid state — an unassigned employee.
2Find such rows with WHERE department IS NULL — never with = NULL.
3If your business forbids parentless rows, add NOT NULL to the FK column.
--key facts
Directionchild (employee) holds the key; parent (department) is referenced
Index the childparent-side deletes check the child column — an index there keeps deletes fast
CASCADE with caredeleting one department silently deleting 10,000 employees deserves a second thought
--use cases
Every normalized schema: orders → customers, comments → posts, employees → departments
Protecting against app bugs: one forgotten check in one script can no longer corrupt the data
Documenting the model: the constraints ARE the ER diagram, executable
Cascading cleanup: session rows vanishing with their user, via ON DELETE CASCADE
--under the hood
Most engines validate FKs with a shared lock on the parent row; high-churn parent tables can become contention hotspots.
PostgreSQL can validate a FK without locking out writes: ADD CONSTRAINT … NOT VALID, then VALIDATE CONSTRAINT later.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.