Coding/Learn/sql/sql foreign key
SQL & Relational Database Engineering Complete Course
01.Introduction & Relational Database Architecture
02.Syntax, Clauses & Execution Order
03.SELECT: Column Projection & Expressions
04.SELECT DISTINCT & Row Deduplication
05.WHERE Clause: Filtering Predicates & Comparison
06.ORDER BY: Sorting, Multi-Column & NULLS Ordering
07.Logical Operators: AND, OR, NOT & Operator Precedence
08.Comments: Single-Line (--), Multi-Line (/* */) & Query Hints
09.Operators: Arithmetic, Bitwise & String Concatenation
10.LIKE Operator & Wildcard Characters (%, _)
11.IN & NOT IN: Membership Operators & Subqueries
12.BETWEEN: Range Filtering for Numbers, Dates & Text
13.NULL Values: Three-Valued Logic, IS NULL & IS NOT NULL
14.Aliases: AS Keyword for Columns & Tables
15.SELECT TOP, LIMIT & OFFSET Pagination
16.INSERT INTO: Single & Multi-Row Insertions
17.UPDATE: Modifying Existing Records & Safe WHERE Rules
18.DELETE: Removing Rows vs TRUNCATE TABLE
19.SELECT INTO & Table Backups (CREATE TABLE AS SELECT)
20.INSERT INTO SELECT: Bulk Data Migration
21.Aggregate Functions: Statistical Summaries
22.MIN() & MAX(): Finding Extremes Across Types
23.COUNT: COUNT(*), COUNT(column) & COUNT(DISTINCT)
24.SUM() & AVG(): Numerical Aggregation & Averages
25.GROUP BY: Aggregation Buckets & Categorical Metrics
26.HAVING: Filtering Aggregated Groups vs WHERE
27.Joins Architecture: Relational Modeling & Venn Diagrams
28.INNER JOIN: Matching Intersections Across Tables
29.LEFT JOIN: Preserving Unmatched Left Rows & Finding Orphans
30.RIGHT JOIN: Preserving Unmatched Right Rows
31.FULL JOIN: Full Outer Join & Complete Reconciliation
32.SELF JOIN: Hierarchies, Trees & Parent-Child Relationships
33.UNION: Combining Result Sets with Automatic Deduplication
34.UNION ALL vs UNION: Performance & Duplicates
35.EXISTS & NOT EXISTS: Correlated Subqueries
36.ANY & ALL: Quantified Comparison Subqueries
37.CASE: Conditional Expressions & Data Transposition
38.Null Functions: COALESCE, IFNULL, ISNULL & NULLIF
39.Stored Procedures, Functions & Query Parameters
40.CREATE & DROP DATABASE: Environment Lifecycle
41.CREATE TABLE: Defining Schemas & Types
42.DROP & TRUNCATE TABLE: Structure vs Data Purging
43.ALTER TABLE: Modifying Columns & Schema Evolution
44.AUTO INCREMENT & Sequences: Identity Generation
45.Date & Time Formats: Timestamp Manipulation
46.Views: Virtual Tables & Security Layers
47.Constraints Overview: Relational Integrity
48.NOT NULL & UNIQUE: Data Invariants
49.PRIMARY KEY: Entity Uniqueness & Clustering
50.FOREIGN KEY: Referential Integrity & Cascades
51.CHECK & DEFAULT: Business Rules at DB Layer
52.CREATE INDEX: B-Trees & Query Optimization
53.Injection Defense: Threat Models & Prevention
54.Parameters & Prepared Statements: Safe Execution
55.Database Engines & Hosting Architecture
56.Dialect References & Data Type Standards
57.Production Best Practices & Query Tuning Checklist
58.Interactive Exercises: Multi-Table Analytics Challenges
59.Comprehensive Assessment & Knowledge Check
60.Capstone Project: Enterprise Analytics Engine
61.Mastery Certification & Graduate Verification
Course Certificate0%

Complete all lessons to earn

LearnSQL FOREIGN KEY: Referential Integrity & Cascades
50 / 61 0%
Lesson 50 of 61
5 mins read

SQL FOREIGN KEY: Referential Integrity & Cascades

PreviousNext Lesson
In Plain English

A `FOREIGN KEY` creates a referential link between a column in a child table and the `PRIMARY KEY` of a parent table. It prevents "orphan records" by blocking insertions of child rows referencing non-existent parents. Cascade actions (`ON DELETE CASCADE`, `ON DELETE SET NULL`, `ON DELETE RESTRICT`) automate parent-child lifecycle management.

The Mental Model

"A `FOREIGN KEY` is like a child holding hands with a parent in a crowd: the child cannot be registered in the park unless the parent is already verified at the entrance."

Deep Dive: How It Works

Referential Integrity: The engine guarantees child foreign key values match an existing parent primary key.

ON DELETE CASCADE: Automatically deletes child rows when the parent entity is deleted.

ON DELETE SET NULL: Clears the child foreign key column to NULL when parent is deleted.

ON DELETE RESTRICT: Forbids deleting parent rows if active child records exist.

Syntax Blueprint

CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL,
  FOREIGN KEY (customer_id) REFERENCES customers(id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
);

Declares foreign key link with cascade actions.

PointCore Rules to Remember

Point star
Prevents Orphan Records: Blocks insertions pointing to deleted or non-existent parent rows.
Point star
Cascade Automation: Deletes dependent sub-records automatically when parent entity is destroyed.
Point star
Foreign Key Indexing: Always create indexes on foreign key columns to avoid table scans during join operations.

Common Beginner Traps & How to Fix Them

Mistake:Using `ON DELETE CASCADE` on critical financial or historical transaction tables.

Why it happens: Deleting a user would silently destroy all financial audit logs and receipt history.

How to fix: Use `ON DELETE RESTRICT` or soft deletes (`is_deleted = 1`) for critical audit trails.

Pro Tip: In SQLite, foreign keys are disabled by default for legacy backward compatibility; execute `PRAGMA foreign_keys = ON;` on every new connection.

Live Interactive Example

Hit Run Code to see it live
Referential Integrity and Cascading Keys
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output Console
Click "Run Code" to view the rendered output.
How it works: Referential link verified and child records joined with parent authors.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Link Categories and Items via Foreign Key

  • PointCreate a `categories (id INTEGER PRIMARY KEY, name TEXT)` table and an `items (id INTEGER PRIMARY KEY, item_name TEXT, category_id INT, FOREIGN KEY (category_id) REFERENCES categories(id))` table.
  • PointInsert category (1, "Electronics") and item (1, "Monitor", 1). Join and select item_name and category name.
1
2
3
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates