DEV Community

MD Mushfiqur Rahman
MD Mushfiqur Rahman

Posted on

🧠 Understanding Keys in Databases

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 column CustomerID that refers to Customers.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)