skip to content

In MySQL's InnoDB, which index becomes a table's clustered index, and what happens when the table has no primary key?

level: middleimportance: must knowfreq 65%

answer

  1. every InnoDB table is clustered
  2. primary key, then a unique index
  3. all key columns NOT NULL
  4. GEN_CLUST_INDEX and a hidden row ID
  5. sql_require_primary_key

basics

~20 s

InnoDB clusters rows on the PRIMARY KEY; without one, on the first UNIQUE index whose key columns are all NOT NULL; failing that, on a hidden GEN_CLUST_INDEX over a 6-byte row ID that no query can use.

solid answer

~40 s

Every InnoDB table is stored as a clustered index: the B-tree whose leaf pages hold the full rows. InnoDB picks it in a fixed order. A declared `PRIMARY KEY` wins. Without one, InnoDB uses the **first `UNIQUE` index whose key columns are all `NOT NULL`**, which may be a wide, randomly ordered column such as an email address. Without that either, it builds a hidden index named `GEN_CLUST_INDEX` on a 6-byte `DB_ROW_ID` assigned in insertion order. Queries cannot filter on that row ID, secondary index entries carry it in place of a key, and under row-based replication each changed row may cost the replica a table scan to find. `sql_require_primary_key` rejects tables without a primary key, and `sql_generate_invisible_primary_key` adds an invisible `my_row_id` key instead.

code

sql · 6 lines
sql
SELECT t.NAME AS table_name, i.NAME AS index_name, i.TYPE
FROM INFORMATION_SCHEMA.INNODB_INDEXES AS i
JOIN INFORMATION_SCHEMA.INNODB_TABLES AS t ON t.TABLE_ID = i.TABLE_ID
WHERE i.TYPE = 1;

SET PERSIST sql_require_primary_key = ON;

go deeper

for a junior

Recall that InnoDB stores every table in clustered-index order, normally the primary key, and that a table should always declare a primary key.

for a middle

Explain the three-step selection rule, what GEN_CLUST_INDEX and DB_ROW_ID are, and why a hidden key cannot be used by queries.

for a senior

Show the operational cost of keyless tables, especially per-row scans under row-based replication, and how to find them through INNODB_INDEXES before they bite.

for a principal

Decide the guard rail: enforce sql_require_primary_key as a schema policy, or rely on generated invisible keys for tables created by tools, and how replicas are covered.

## Every InnoDB table is a clustered index InnoDB never stores a table as an unordered heap. Each table has exactly one **clustered index**, a B-tree whose leaf pages contain the complete rows, ordered by the clustered index key. Every other index is a **secondary index**, and each of its entries stores the clustered key value so InnoDB can find the row. Which index InnoDB clusters on therefore decides the physical order of the table and the size of every secondary entry. ## The selection rule InnoDB applies three rules, in order: 1. **A declared `PRIMARY KEY`** becomes the clustered index. 2. **Otherwise, the first `UNIQUE` index whose key columns are all `NOT NULL`** becomes the clustered index. "First" refers to index order in the table definition, which nobody chose for this purpose. 3. **Otherwise, InnoDB generates a hidden clustered index called `GEN_CLUST_INDEX`** on a synthetic `DB_ROW_ID` column. The row ID is a 6-byte value that increases as rows are inserted, so rows end up in insertion order. Besides the user columns, every clustered index record carries hidden system fields: a 6-byte `DB_TRX_ID` (the last transaction to change the row) and a 7-byte `DB_ROLL_PTR` pointing at undo information. `DB_ROW_ID` is stored only when rule 3 applied. ## Why rules 2 and 3 cause trouble Rule 2 surprises teams who never declared a key: - A table with `UNIQUE (email)` and `email NOT NULL` is silently clustered on email, so inserts land at random places in the B-tree and every secondary index entry carries the full email string. - Adding a `PRIMARY KEY` later rebuilds the table, because restructuring the clustered index always copies the table data. Rule 3 is worse: - **The row ID is internal.** It is not a column you can select, join on or put in a `WHERE` clause, so the cheapest possible lookup path is unusable. - **Secondary indexes carry the row ID.** They still work, but you cannot exploit the clustering for range reads on a meaningful key. - **Row-based replication suffers.** When an `UPDATE` or `DELETE` touches many rows of a table with no primary key, the source does one scan but the replica applies one row event at a time, and each event may need its own table scan to find the row. A change that took seconds on the source can leave a replica hours behind. - **Lock reports look odd.** Locks on such tables appear against `GEN_CLUST_INDEX` in lock diagnostics. | Table defines | Clustered index | Key usable by queries? | |---|---|---| | `PRIMARY KEY (id)` | `PRIMARY` on `id` | Yes | | No primary key, `UNIQUE (email)` with `email NOT NULL` | The `email` unique index | Yes, but possibly wide and randomly ordered | | No primary key, no suitable unique index | `GEN_CLUST_INDEX` on hidden `DB_ROW_ID` | No | ## Seeing which rule applied `INFORMATION_SCHEMA.INNODB_INDEXES` lists every InnoDB index with a numeric `TYPE`: `3` is a clustered index, `1` is an automatically generated `GEN_CLUST_INDEX`, `2` a unique non-clustered index and `0` an ordinary secondary index. A legacy schema converted from another engine is the usual place to find `TYPE = 1`. ## Server-side guard rails MySQL 8.4 offers two system variables, both `OFF` by default and settable globally or per session: - **`sql_require_primary_key`** makes `CREATE TABLE` without a primary key fail (including `CREATE TABLE ... LIKE`, and `CREATE TABLE ... SELECT` without a key definition), and makes an `ALTER TABLE` that drops the primary key fail unless the same statement adds one, even when a `UNIQUE NOT NULL` index remains. Changes to its value are replicated. - **`sql_generate_invisible_primary_key`** makes the server add an invisible column `my_row_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT` and a primary key on it to any InnoDB table created without one. The column does not appear in `SELECT *`; you can make it visible with `ALTER TABLE ... ALTER COLUMN my_row_id SET VISIBLE`. Replication applier threads ignore this variable, so replicas only generate such keys when the replication channel is configured with `REQUIRE_TABLE_PRIMARY_KEY_CHECK = GENERATE`. The first is a policy that forces developers to decide; the second is a safety net for tools and frameworks that create tables you do not control. Either is better than discovering `GEN_CLUST_INDEX` on a busy table. How wide a primary key should be, and whether a random key such as a UUID belongs there, is the general clustered-storage trade-off; the InnoDB-specific lesson is that *not choosing* is itself a choice InnoDB makes for you, and usually a poor one.

  • What are the hidden DB_TRX_ID and DB_ROLL_PTR fields in every InnoDB clustered index record for?
    `DB_TRX_ID` (6 bytes) records the last transaction that inserted or updated the row; a delete is an update that sets a deleted bit. `DB_ROLL_PTR` (7 bytes) points to an undo log record in a rollback segment, from which InnoDB rebuilds the earlier version of the row for rollback and for consistent reads. They exist whatever the clustering key is.
  • Why does sql_generate_invisible_primary_key not protect replicas automatically?
    The variable is not replicated, and replication applier threads ignore it even when it is set on the replica. A table created without a key on the source therefore arrives without one on the replica unless the channel is configured with `REQUIRE_TABLE_PRIMARY_KEY_CHECK = GENERATE` in `CHANGE REPLICATION SOURCE TO`.

  • An InnoDB table without a primary key is stored as an unordered heap.
  • InnoDB clusters on whichever index was created first, unique or not.
  • You can query the hidden row ID through _rowid like any column.
  • A nullable UNIQUE column can become the clustered index if no primary key exists.
  • sql_require_primary_key is ON by default in MySQL 8.4.