✏️ Explanatory Question

What are the different types of keys in MySQL?

👁 11 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

7

What are the different types of keys in MySQL?

Level: Basic — Keys are the backbone of relational databases; interviewers expect all major types.

A key is a column (or set of columns) used to uniquely identify rows and establish relationships between tables. MySQL supports several types of keys, each with a specific purpose.

The Main Types of Keys

  • Primary Key: Uniquely identifies each row. Cannot be NULL and must be unique. A table can have only one primary key.
  • Candidate Key: A column (or set) that qualifies to be a primary key. One candidate key becomes the primary key; the rest are alternate keys.
  • Alternate Key: A candidate key that was not chosen as the primary key.
  • Unique Key: Ensures all values in a column are unique, but allows one NULL value.
  • Foreign Key: Links two tables by referencing the primary key of another table (enforces referential integrity).
  • Composite Key: A key made up of two or more columns to uniquely identify a row.
  • Super Key: Any set of columns that uniquely identifies a row (a superset of candidate keys).
Key hierarchy to remember: Super Key ⊃ Candidate Key ⊃ Primary Key. Every primary key is a candidate key, and every candidate key is a super key — but not the other way around.

Primary Key vs Unique Key vs Foreign Key

Feature Primary Key Unique Key Foreign Key
Uniqueness Yes Yes Can repeat
NULL allowed? No Yes (one NULL) Yes
Number per table Only one Many Many
Purpose Identify each row Prevent duplicates Link tables

Quick Example

CREATE TABLE departments (
    dept_id   INT PRIMARY KEY,          -- Primary Key
    dept_name VARCHAR(50) UNIQUE        -- Unique Key
);

CREATE TABLE employees (
    emp_id   INT PRIMARY KEY,           -- Primary Key
    email    VARCHAR(100) UNIQUE,       -- Unique Key (one NULL allowed)
    dept_id  INT,
    -- Foreign Key linking to departments
    FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);

-- Composite Key example (two columns together)
CREATE TABLE enrollment (
    student_id INT,
    course_id  INT,
    PRIMARY KEY (student_id, course_id)  -- Composite Key
);
Interviewer tip: Start by naming Primary, Foreign, Unique, and Composite keys (the most-used four), then mention Candidate, Alternate, and Super keys to show deeper knowledge.