Differences between Primary Key and Foreign Key
Estimated study time: 7 minutes. Two of the most important keys in relational database design.
Primary keys and foreign keys are both used to establish structure and relationships in a relational database, but they serve very different purposes. Understanding this difference is fundamental to designing correct, well-normalized tables.
What is a Primary Key?
A primary key uniquely identifies each row in its own table. It cannot contain NULL values, and a table can have only one primary key.
CREATE TABLE Departments ( DeptID INT PRIMARY KEY, DeptName VARCHAR(50) );
What is a Foreign Key?
A foreign key is a column (or set of columns) in one table that references the primary key of another table. It's used to link two tables together and enforce referential integrity.
CREATE TABLE Employees ( EmpID INT PRIMARY KEY, EmpName VARCHAR(50), DeptID INT FOREIGN KEY REFERENCES Departments(DeptID) );
Key Differences
- Purpose: Primary Key — identifies rows uniquely in its own table | Foreign Key — links to a primary key in another table
- NULL values: Primary Key — not allowed | Foreign Key — allowed (unless explicitly restricted)
- Duplicates: Primary Key — not allowed | Foreign Key — allowed, since many rows can reference the same parent row
- Count per table: Primary Key — one | Foreign Key — a table can have multiple foreign keys
Why This Matters
Together, primary and foreign keys are what let relational databases avoid data duplication. Instead of repeating department details in every employee row, you store them once in Departments and simply reference the ID.