Primary Keys, Foreign Keys, Referential Integrity & Constraints
Overview & Learning Objectives
Relational databases derive their power from referential integrity: guaranteeing that relationships between entities remain consistent and valid. Primary keys enforce entity uniqueness, while foreign keys establish parent-child links that prevent orphaned transactional records. MySQL's InnoDB engine strictly validates constraints on every insert, update, and delete.
- Define single-column and composite Primary Keys in MySQL.
- Establish Foreign Key constraints with `ON DELETE CASCADE` and `ON DELETE SET NULL`.
- Implement `NOT NULL`, `UNIQUE`, and `CHECK` constraints to validate business rules at the database engine level.
Industry Standard
Standard: Fintech engineering standards at Stripe mandate strict foreign key enforcement to prevent orphaned billing records or unmapped transaction charges.
Real-World Example: ScoopCraft Orders and Order Items Relational Schema
ScoopCraft links orders to customers and items to orders, ensuring no order can exist for a deleted customer.
| Parent Table | Parent Key | Child Table | Foreign Key | Cascade Action |
|---|---|---|---|---|
| customers | customer_id | orders | customer_id | ON DELETE RESTRICT (Prevents deleting active buyers) |
| orders | order_id | order_items | order_id | ON DELETE CASCADE (Deleting order removes line items) |
Syntax & Core SQL Implementation
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
order_total DECIMAL(10,2) NOT NULL,
CONSTRAINT chk_total CHECK (order_total >= 0),
CONSTRAINT fk_customer FOREIGN KEY (customer_id)
REFERENCES customers(customer_id)
ON DELETE RESTRICT
ON UPDATE CASCADE
) ENGINE=InnoDB;
Parameters & Arguments Breakdown
PRIMARY KEY: Unique, non-null index uniquely identifying each table row.FOREIGN KEY: Column referencing the primary key of another table to maintain relational integrity.ON DELETE CASCADE: Automatically deletes child rows when the parent record is deleted.CHECK: Validates that values satisfy a boolean predicate expression before allowing insertion.
Sample Walkthrough (Q&A)
Question: What happens when you try to delete a customer who has existing orders under ON DELETE RESTRICT?
SQL Pattern: DELETE FROM customers WHERE customer_id = 101;
Result: Error 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails
Explanation: RESTRICT halts the deletion, protecting the child order records from becoming orphaned.
Common Mistakes & Limitations
- Using `ON DELETE CASCADE` carelessly on parent tables, causing accidental mass deletions of historical financial orders.
- Attempting to create foreign keys referencing columns that lack an index or primary key in the parent table.
Keyboard Shortcuts (MySQL Workbench)
| Action | Windows | Mac |
|---|---|---|
| View Foreign Keys in MySQL | SELECT * FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_NAME='orders'; | SELECT * FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_NAME='orders'; |
Pro Tips & Modern Best Practices
- In MySQL 8.0.16+, `CHECK` constraints are fully enforced (in older MySQL 5.7, CHECK was parsed but completely ignored!).
- Name your constraints explicitly (`CONSTRAINT fk_orders_customers ...`) so error logs immediately identify which constraint failed.