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_idis the primary key.orders.customer_idis 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!
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
Β© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
