What is a primary key?

BeginnerConceptMySQL
Answer

Short answer

A primary key is a column (or set of columns) that uniquely identifies each row in a table. It can't be NULL and can't repeat. Every table should have one; usually it's an auto-incrementing id.

Example

CREATE TABLE customers (
  id INT AUTO_INCREMENT PRIMARY KEY,   -- 1, 2, 3 ... assigned automatically
  email VARCHAR(150) NOT NULL UNIQUE,
  name VARCHAR(100)
);
INSERT INTO customers (email, name) VALUES ('[email protected]', 'Asha');   -- id = 1

Why it matters

  • Rows can be found, updated and deleted precisely: WHERE id = 42.
  • Other tables reference it with foreign keys.
  • In InnoDB, the table is physically stored ordered by the primary key (clustered index), so lookups by it are very fast.
  • Replication (especially row-based) and many tools work much better when every table has a primary key.

Primary key vs unique key

Primary key Unique key
How many per table One Many
NULL allowed No Yes (in MySQL)

What to say in the interview

"A primary key uniquely identifies each row, is non-null and unique, and is what foreign keys reference. In InnoDB it's also the clustered index, so every table should have one."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MySQL basics

More on MySQL