Primary Key vs Foreign Key in DBMS (With Examples)
Introduction
In relational
databases, Primary Keys and Foreign Keys are essential for
organizing data and creating relationships between tables. Many students
confuse these two concepts, but the difference is simple once you understand
their roles.
This guide
explains Primary Key vs Foreign Key clearly with examples.
What is a
Primary Key?
A Primary
Key is a column (or set of columns) that uniquely identifies each record in
a table.
It ensures that no two rows have the
same identity.
Key
Features of Primary Key
- Must contain unique values
- Cannot contain NULL values
- Only one primary key per table
- Used to identify each record
Example
Students
table
|
StudentID |
Name |
Age |
|
101 |
Ali |
21 |
|
102 |
Sara |
22 |
Here, StudentID is the Primary
Key because it uniquely identifies each student.
What is a
Foreign Key?
A Foreign
Key is a column in one table that refers to the Primary Key in another
table.
It is used to create a relationship
between tables.
Key
Features of Foreign Key
- Can contain duplicate values
- Can contain NULL values
(in most cases)
- Multiple foreign keys allowed in
a table
- Maintains referential
integrity
Example of
Foreign Key
Students
table (Parent table)
|
StudentID
(PK) |
Name |
|
101 |
Ali |
|
102 |
Sara |
Orders
table (Child table)
|
OrderID |
StudentID
(FK) |
Course |
|
1 |
101 |
DBMS |
|
2 |
101 |
SQL |
|
3 |
102 |
Networking |
Here:
- StudentID in Students → Primary Key
- StudentID in Orders → Foreign Key
This links
orders to the correct student.
Primary
Key vs Foreign Key (Comparison Table)
|
Feature |
Primary
Key |
Foreign
Key |
|
Purpose |
Uniquely
identifies records |
Links two
tables |
|
Uniqueness |
Must be
unique |
Can have
duplicates |
|
NULL values |
Not allowed |
Allowed
(usually) |
|
Number per
table |
Only one |
Multiple
allowed |
|
Location |
Same table
it identifies |
References
another table |
|
Role |
Parent
identifier |
Relationship
creator |
Simple
Real-Life Analogy
Think of:
- Primary Key → Student NIC number (unique
identity)
- Foreign Key → Student ID written in exam
records
The foreign
key points back to the student’s unique identity.
SQL
Example
Create
Students Table
CREATE TABLE
Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50)
);
Create
Orders Table with Foreign Key
CREATE TABLE
Orders (
OrderID INT PRIMARY KEY,
StudentID INT,
Course VARCHAR(50),
FOREIGN KEY (StudentID) REFERENCES
Students(StudentID)
);
Why These
Keys Are Important
Primary
Key helps to:
- Uniquely identify data
- Prevent duplicate records
- Improve indexing
Foreign
Key helps to:
- Maintain relationships
- Ensure data consistency
- Prevent invalid data entry
Conclusion
A Primary Key
uniquely identifies each record in a table, while a Foreign Key creates
relationships between tables by referencing the Primary Key of another table.
Both are essential for maintaining organized, accurate, and relational
databases.

Comments
Post a Comment