Why does the choice of primary key matter so much in InnoDB?
Because InnoDB stores rows inside the primary-key index (a clustered index):
- Rows are physically ordered by the primary key.
- Every secondary index entry contains the primary key, so a big primary key makes every index bigger.
- A secondary-index lookup that needs other columns does a second lookup in the clustered index ("bookmark lookup"), unless the index covers the query.
Good primary keys
- Short and monotonically increasing:
BIGINT AUTO_INCREMENT. New rows append at the end of the B-tree, pages fill sequentially, and inserts are fast. - Random UUIDs (v4) as
CHAR(36)are the worst case: 36 bytes copied into every index, and inserts land on random pages, causing page splits, fragmentation and poor cache use. - If you need UUIDs (generated by clients, merging data across shards), store them as
BINARY(16), prefer time-ordered UUIDs (UUIDv7, or MySQL'sUUID_TO_BIN(uuid, 1)swap flag for v1), or keep anAUTO_INCREMENTkey internally and expose a UUID as a unique secondary column.
Without an explicit primary key
InnoDB uses the first NOT NULL UNIQUE index or creates a hidden 6-byte row id, which is shared globally and can become a contention point. Always define one; Group Replication requires it.
Example
sql
-- Public UUID for APIs, compact sequential key for storage and joins
CREATE TABLE orders (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
public_id BINARY(16) NOT NULL,
customer_id BIGINT UNSIGNED NOT NULL,
status ENUM('NEW','PAID','SHIPPED','CANCELLED') NOT NULL,
created_at DATETIME(3) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_orders_public (public_id),
KEY idx_orders_customer_created (customer_id, created_at) -- also implicitly contains id
) ENGINE=InnoDB;
INSERT INTO orders (public_id, customer_id, status, created_at)
VALUES (UUID_TO_BIN(UUID(), 1), 42, 'NEW', NOW(3));
SELECT BIN_TO_UUID(public_id, 1) AS public_id, status FROM orders WHERE customer_id = 42;Follow-up questions interviewers ask
Try answering each one before you open it.
Why is the index (customer_id, created_at) covering for "SELECT id ... WHERE customer_id = ?"
Because every InnoDB secondary index already includes the primary key. The query reads only the secondary index, with no lookup into the clustered index; EXPLAIN shows "Using index".