If you're learning databases, you've probably come across terms like Primary Key, Super Key, and Foreign Key. These "keys" are the backbone of organizing data in relational databases.
Letβs break them down simply π
π What is a Key?
A key is an attribute (column) β or a set of attributes β that helps uniquely identify each row in a table. Without keys, youβd struggle to find, update, or relate specific data efficiently.
π§© 1. Super Key
A Super Key is any combination of columns that can uniquely identify a row in a table.
π Example: In a Students
table:
StudentID
Email
StudentID + Name
All of these can be Super Keys if they uniquely identify a student.
π§© 2. Candidate Key
A Candidate Key is a minimal Super Key β the most efficient one without extra columns.
β
If both StudentID
and Email
can uniquely identify a student, then:
-
StudentID
β Candidate Key -
Email
β Candidate Key -
StudentID + Email
β β Not a Candidate Key (extra column)
π§© 3. Primary Key
A Primary Key is one Candidate Key chosen to be the main identifier of a table.
β Rules:
- Must be unique
- Cannot be NULL
π‘ Most tables use an ID
column as the Primary Key.
π§© 4. Foreign Key
A Foreign Key connects one table to another. It references the Primary Key of another table.
π Example:
-
Orders
table has a columnCustomerID
that refers toCustomers.ID
This builds relationships between tables β the heart of relational databases.
π 5. Composite Key
A Composite Key uses two or more columns together to uniquely identify a row.
π Example:
In a CourseRegistrations
table:
-
StudentID + CourseID
β Composite Key (to avoid duplicate enrollments)
TL;DR
π Key Type | π Purpose |
---|---|
Super Key | Any column(s) that uniquely identify a row |
Candidate Key | Minimal Super Key (no unnecessary fields) |
Primary Key | Chosen Candidate Key; must be unique + not NULL |
Foreign Key | Links rows between tables |
Composite Key | Uses multiple columns to uniquely identify a row |
π¬ Got questions about how these work in real SQL or project setups? Letβs discuss in the comments! π
Top comments (0)