4. Foreign Keys & Data 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.
Rule: Every customer_id in ORDERS must exist in CUSTOMERS.id. This ensures no orphaned orders!
-- 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).
-- 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?