What is a foreign key?
A foreign key is a column (or a set of columns) in one table that links to the primary key of another table. It is used to establish a relationship between two tables and maintain referential integrity in a database.
๐ Purpose of a Foreign Key:
- To connect tables logically (e.g., orders linked to customers).
- To ensure consistency, meaning only valid data that exists in the referenced table can be inserted.
โ Example:
Letโs say we have two tables:
-- Parent table
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100)
);
-- Child table
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
Here:
customers.customer_id
is the primary key.orders.customer_id
is the foreign key that refers tocustomers.customer_id
.
So, you canโt insert an order with a customer_id
that doesnโt exist in the customers
table.
๐ Key Rules of Foreign Keys:
Rule | Description |
---|---|
Referential Integrity | Prevents invalid references (e.g., referencing a non-existent customer). |
On Delete / On Update | You can define what happens when the referenced row is deleted or updated (e.g., CASCADE , SET NULL , RESTRICT ). |
๐ Example with ON DELETE CASCADE:
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE
This means: if a customer is deleted, all their related orders are also deleted automatically.
๐ง Summary:
Feature | Foreign Key |
---|---|
Links to | Primary Key in another table |
Allows NULLs | โ Yes (unless specified NOT NULL) |
Allows duplicates | โ Yes (unless combined with other constraints) |
Ensures integrity | โ Yes |
Want an ER diagram or visual to go along with this? I can mock one up for you!
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.