A foreign key is a column or set of columns in a table that refers to the primary key of another table. It is used to establish a relationship between two tables.
When we study databases, one important idea is how different tables connect to each other.
Just like in real life a student belongs to a class, or an employee belongs to a department, database tables also have relationships.
To maintain these relationships in a clear and reliable way, SQL uses something called a foreign key.
A foreign key is a column in one table that refers to the primary key of another table.
It acts like a link or a bridge that connects two tables together, ensuring that the relationship between them stays accurate.
I often explain this to my students using a simple analogy:
If the primary key is a person’s unique identity, then the foreign key is like a reference to that identity in another list.
It tells us “this row belongs to that record in the other table.”
Key points about a foreign key:
- It establishes a relationship between two tables.
- It ensures data integrity—you cannot enter a value that doesn’t exist in the parent table.
- It prevents accidental deletion of important linked data.
- It helps maintain consistency across related tables.
Simple Example
Imagine two tables:
1. Departments Table
| DeptID (Primary Key) | DeptName |
|---|---|
| 10 | Finance |
| 20 | HR |
| 30 | IT |
2. Employees Table
| EmpID | EmpName | DeptID (Foreign Key) |
|---|---|---|
| 1 | Aditi | 10 |
| 2 | Rohan | 30 |
| 3 | Meera | 20 |
Here, DeptID in the Employees table is a foreign key pointing to
DeptID in the Departments table.
That means:
- Employee Aditi works in the Finance department
- Rohan works in IT
- Meera works in HR
SQL will not allow you to enter a DeptID like “50” in Employees, because no such department exists in the Departments table.
Why is a foreign key important?
A foreign key ensures:
- Data remains logically connected
- No invalid values are inserted
- Related records stay consistent
- The database mirrors real-world relationships correctly
Without foreign keys, databases can quickly become messy, full of mismatched or orphaned records.