MySQL Primary Key

A primary key is the constraint that gives every row in a table a stable, unique identity, and it underpins how other tables reference that row.

What a Primary Key Guarantees

A PRIMARY KEY constraint combines UNIQUE and NOT NULL: every value in the key column (or columns) must be different from every other row's, and none of them may be NULL. A table can have at most one primary key, though that key may span multiple columns as a composite key.

Single-column primary key

CREATE TABLE students (
  student_id INT PRIMARY KEY AUTO_INCREMENT,
  full_name VARCHAR(100) NOT NULL
);

Composite Primary Keys

When no single column is naturally unique but a combination of columns is, you can declare a composite primary key by listing more than one column inside a table-level PRIMARY KEY clause. A common example is a join table connecting two other tables, where the pair of foreign keys together identifies one row.

Composite key on a join table

CREATE TABLE enrollments (
  student_id INT NOT NULL,
  course_id INT NOT NULL,
  enrolled_on DATE NOT NULL,
  PRIMARY KEY (student_id, course_id)
);

Adding a Primary Key Later

If a table was created without a primary key, one can be added afterward, provided the target column already contains unique, non-null values (or the table is empty).

Add a primary key to an existing table

ALTER TABLE students
  ADD PRIMARY KEY (student_id);
  • MySQL automatically creates a unique index on the primary key, which also speeds up lookups by that column.
  • InnoDB physically stores table rows ordered by the primary key (a clustered index), so a well-chosen key affects performance, not just correctness.
  • AUTO_INCREMENT is commonly paired with an integer primary key so the database generates each new ID automatically.
Key styleExampleWhen to use
Surrogate (auto-increment integer)id INT PRIMARY KEY AUTO_INCREMENTDefault choice; simple, stable, never changes
Natural keyPRIMARY KEY (email)When a real-world value is truly unique and stable
Composite keyPRIMARY KEY (student_id, course_id)Join/link tables with no single unique column
Note: A surrogate key (an artificial auto-incrementing ID) is usually safer long-term than a natural key like an email address, because natural values occasionally need to change, and a primary key should not.
Note: Dropping a primary key with ALTER TABLE ... DROP PRIMARY KEY also removes its associated AUTO_INCREMENT behavior on that column, and will fail if another table's foreign key currently references it.