Lesson

MySQL PRIMARY KEY

10 min reading
Free Course

MySQL PRIMARY KEY: Uniquely Identifying Every Row

A MySQL PRIMARY KEY uniquely identifies every record in a table using one column or a small group of columns. A primary key enforces both NOT NULL and UNIQUE automatically, and each table can define at most one PRIMARY KEY.

Why InnoDB Requires a Primary Key

In InnoDB, the PRIMARY KEY is not just a constraint—it is the clustered index that physically sorts and stores the entire table's rows on disk. Every secondary index you add also appends the primary key value internally to point back to the row.

Practical SQL Examples

Use a compact auto-increment integer for standard entity tables, and a composite primary key for pure many-to-many join tables:

-- Single-column surrogate primary key
CREATE TABLE demo_customers (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE
);

-- Composite primary key on a many-to-many tag join table
CREATE TABLE demo_product_tags (
    product_id BIGINT UNSIGNED NOT NULL,
    tag_id INT UNSIGNED NOT NULL,
    PRIMARY KEY (product_id, tag_id)
);

Common Mistakes and Best Practices

  • Keep Primary Keys Narrow and Sequential: Because every secondary index stores a copy of the primary key, using a bulky 36-byte CHAR(36) random UUID string bloats every index and causes page splits. Use sequential BIGINT UNSIGNED AUTO_INCREMENT (or binary UUID_TO_BIN(UUID(), 1) if distributed IDs are mandatory).
  • Never Change Primary Key Values: Treat primary keys as immutable identifiers; updating a primary key forces InnoDB to move the physical row and update all child foreign keys and secondary indexes.

Frequently Asked Questions

Can a PRIMARY KEY contain NULL?

No, MySQL rejects NULL in any column belonging to a PRIMARY KEY.

What happens if an InnoDB table has no PRIMARY KEY?

InnoDB falls back to the first UNIQUE NOT NULL index, or generates a hidden 6-byte row ID that cannot be queried and hurts replication performance.

Should I use email as a PRIMARY KEY?

No, emails change when users update accounts; keep email as a UNIQUE index and use an immutable id as the PRIMARY KEY.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum