Different Types of SQL Keys
Estimated study time: 11 minutes. Every kind of key SQL uses to identify and relate data.
Keys are how relational databases guarantee uniqueness and define relationships between tables. There are more types than most people expect — here's a clear breakdown of each.
Primary Key
Uniquely identifies each row in a table. Cannot contain NULL, and a table can only have one.
CREATE TABLE Students (StudentID INT PRIMARY KEY, Name VARCHAR(50));
Foreign Key
A column that references the primary key of another table, enforcing referential integrity.
CREATE TABLE Enrollments ( EnrollmentID INT PRIMARY KEY, StudentID INT FOREIGN KEY REFERENCES Students(StudentID) );
Candidate Key
Any column (or combination of columns) that could qualify as the primary key. A table can have multiple candidate keys, but only one becomes the primary key.
Unique Key
Enforces uniqueness like a primary key, but allows one NULL value and a table can have several unique keys.
CREATE TABLE Students (Email VARCHAR(100) UNIQUE);
Composite Key
A primary key made up of two or more columns together, used when no single column is unique on its own.
CREATE TABLE OrderItems ( OrderID INT, ProductID INT, PRIMARY KEY (OrderID, ProductID) );
Super Key
Any set of columns that can uniquely identify a row — every primary key and candidate key is a super key, but not every super key is minimal.
Quick Comparison
- Primary Key: one per table, no NULLs
- Foreign Key: links to another table's primary key
- Unique Key: multiple allowed, one NULL permitted
- Composite Key: multiple columns forming one key