3.5 Hours

4. Foreign Keys & Data Integrity

Integrity

Foreign keys are the foundation of relational integrity. They ensure that data references are valid and that relationships are maintained. Foreign keys prevent orphaned records and enforce referential integrity. Understanding foreign keys is essential for designing reliable databases.

A foreign key is a column or set of columns that references the primary key of another table. It ensures that every value in the foreign key column exists in the referenced table. Foreign keys can also define what happens when a referenced row is deleted or updated (ON DELETE, ON UPDATE). This module covers foreign key design, cascading actions, and integrity constraints.

Foreign Key Basics

A foreign key establishes a link between two tables. The foreign key in the child table references the primary key of the parent table. This ensures that every child row has a valid parent. Foreign keys enforce referential integrity. They prevent orphaned records.

Parent Table: CUSTOMERSChild Table: ORDERS
id (PK) | name | email
1 | Alice | alice@...
2 | Bob | bob@...
3 | Carol | carol@...
id (PK) | customer_id (FK) | total
101 | 1 | 150.00
102 | 2 | 75.50
103 | 1 | 200.00
104 | 3 | 45.25

Rule: Every customer_id in ORDERS must exist in CUSTOMERS.id. This ensures no orphaned orders!

SQL
-- Foreign key basics
CREATE TABLE customers (
  id INT PRIMARY KEY,
  name TEXT NOT NULL
);

CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,
  order_date DATE,
  total DECIMAL(10,2),
  CONSTRAINT fk_orders_customer
    FOREIGN KEY (customer_id)
    REFERENCES customers(id)
);

ON DELETE and ON UPDATE Actions

When a referenced row is deleted or updated, you can define what happens to the referencing rows. The options are: CASCADE (delete/update the referencing rows), SET NULL (set the foreign key to NULL), RESTRICT (prevent the operation), and NO ACTION (similar to RESTRICT).

ActionWhat Happens When Parent is DeletedUse Case
CASCADEChild rows are automatically deletedOrders should be deleted when customer is deleted
SET NULLForeign key is set to NULLRelationship is optional
RESTRICTDelete is prevented if children existCannot delete customer with orders
SQL
-- ON DELETE CASCADE
CREATE TABLE orders_cascade (
  id INT PRIMARY KEY,
  customer_id INT,
  order_date DATE,
  total DECIMAL(10,2),
  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
);

-- ON DELETE SET NULL
CREATE TABLE orders_set_null (
  id INT PRIMARY KEY,
  customer_id INT,
  order_date DATE,
  total DECIMAL(10,2),
  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE SET NULL
);

-- ON DELETE RESTRICT
CREATE TABLE orders_restrict (
  id INT PRIMARY KEY,
  customer_id INT,
  order_date DATE,
  total DECIMAL(10,2),
  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE RESTRICT
);

Knowledge Check

Ready to test your understanding of 4. Foreign Keys & Data Integrity?

Back