skip to content

In MySQL with InnoDB, what does a secondary index entry contain, and how does the optimizer use the primary key columns stored there?

level: middleimportance: must knowfreq 65%

answer

  1. what points from index to row
  2. no physical address stored
  3. the key is silently longer
  4. use_index_extensions in optimizer_switch

basics

~20 s

Each InnoDB secondary index entry holds the indexed columns followed by the row's primary key, which is used to find the row. The optimizer treats those appended columns as extra key parts for lookups, sorting and covering.

solid answer

~40 s

In InnoDB a secondary index entry is the indexed columns plus the row's primary key columns, not a physical row address; the primary key is then used to search the clustered index for the full row. So `INDEX k_d (d)` on a table with `PRIMARY KEY (i1, i2)` is internally `(d, i1, i2)`. The optimizer exploits this through index extensions (`use_index_extensions`, on by default in `optimizer_switch`): it can use the appended columns for `ref`, `range` and `index_merge` access, for sorting and for `MIN()`/`MAX()`. A query selecting only `d` and the primary key columns is covered, so EXPLAIN shows `Using index`, and `key_len` grows when a predicate on `i1` is used as a second key part. The cost is that every secondary index repeats the primary key, so a wide primary key widens them all.

code

sql · 12 lines
sql
CREATE TABLE customers (
  id    BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) NOT NULL,
  name  VARCHAR(100) NOT NULL,
  KEY idx_email (email)
) ENGINE=InnoDB;

-- Covered: the index holds email, and InnoDB appends id to every entry
EXPLAIN SELECT id FROM customers WHERE email = '[email protected]';

-- Not covered: name lives only in the clustered index
EXPLAIN SELECT id, name FROM customers WHERE email = '[email protected]';

go deeper

for a junior

Remember that an InnoDB secondary index entry ends with the row's primary key, and that the primary key is what finds the row.

for a middle

Explain index extensions: how the appended columns show up in key_len, ref and Using index, and that use_index_extensions is on by default.

for a senior

Connect primary key width to every secondary index's size and buffer pool footprint, and read an EXPLAIN that only makes sense once the hidden columns are counted.

for a principal

Treat the primary key as a fleet-wide cost multiplier: set a team default for narrow surrogate keys and decide when a natural key's convenience justifies its repeated width.

## What an InnoDB secondary index entry holds InnoDB stores each table as a **clustered index**: a B-tree ordered by the primary key whose leaf pages hold the complete rows. Every other index is a **secondary index**, a separate B-tree. The manual states the layout plainly: each secondary index record contains the indexed columns **and the primary key columns** of the row, and InnoDB uses that primary key value to look the row up in the clustered index. Two consequences follow straight away: - A secondary index never stores a page number or a slot. When a page split moves a row inside the clustered index, no secondary index has to change, because the primary key that finds the row has not changed. - A lookup through a secondary index that needs columns the index lacks costs **two B-tree descents**: one in the secondary index, one in the clustered index. That double lookup in general is covered in the lesson on secondary-index lookups; what matters here is what MySQL does with the extra columns. ## Index extensions: the optimizer sees the hidden columns Because the primary key is physically there, MySQL's optimizer treats an InnoDB secondary index as **extended** by the primary key columns. Take this table: ```sql CREATE TABLE t1 ( i1 INT NOT NULL DEFAULT 0, i2 INT NOT NULL DEFAULT 0, d DATE DEFAULT NULL, PRIMARY KEY (i1, i2), INDEX k_d (d) ) ENGINE = InnoDB; ``` Internally `k_d` is `(d, i1, i2)`. For `SELECT COUNT(*) FROM t1 WHERE i1 = 3 AND d = '2000-01-01'`, the manual shows the effect of the extension in EXPLAIN: | EXPLAIN column | Extensions off | Extensions on | |---|---|---| | `key` | `k_d` | `k_d` | | `key_len` | `4` (only `d`) | `8` (`d` and `i1`) | | `ref` | `const` | `const,const` | | `rows` | 5 | 1 | | `Extra` | `Using where; Using index` | `Using index` | The optimizer can use extended secondary indexes for `ref`, `range` and `index_merge` access, for Loose Index Scan, for join and sorting optimisation, and for `MIN()`/`MAX()` optimisation. The behaviour is controlled by the `use_index_extensions` flag of `optimizer_switch`, which is **on by default**; `SET optimizer_switch = 'use_index_extensions=off'` exists to test whether turning it off ever helps. The usual limits still apply to the extended key: at most **16 key parts** and a maximum key length of **3072 bytes**. ## Covering queries you did not plan for The appended primary key makes some queries index-only without any extra columns: - `SELECT id FROM customers WHERE email = ?` with `INDEX (email)` and `PRIMARY KEY (id)` reads only the secondary index, so `Extra` shows `Using index`. - The manual notes that in InnoDB a secondary index can cover the selected columns **even when the query also selects the primary key**, because the primary key is stored with each entry. - `ORDER BY email, id` can be read in index order from the same index, since entries with equal `email` values are already ordered by `id`. ## What it costs: the primary key is copied everywhere 1. **Every secondary index repeats the primary key.** A 4-byte `INT` or 8-byte `BIGINT` key adds little; a 36-character string key stored as `CHAR(36)` in `utf8mb4`, or a multi-column natural key, is repeated in every entry of every secondary index. 2. **Wider entries mean fewer entries per 16 KB page** (the default `innodb_page_size`), so a larger index, more pages in the buffer pool and more I/O for the same rows. 3. **Changing a primary key value rewrites every secondary index entry** for that row, as well as moving the row in the clustered index. The manual's advice follows from this: if the primary key is long, the secondary indexes use more space, so a short primary key is an advantage. Choosing the primary key in general, natural or surrogate, is a schema-design subject; the MySQL-specific point is that the price is paid once per secondary index. ## Reading it in EXPLAIN - `key_len` larger than the declared index columns means the optimizer is using appended primary key parts. - `Using index` on a query that selects primary key columns not listed in the index definition is the extension at work, not a mistake. - `possible_keys` can stay the same while `rows` drops sharply once the extension is used.

  • In MySQL with InnoDB, why can EXPLAIN show Using index for SELECT id, email FROM customers WHERE email = ? when idx_email lists only email?
    Every InnoDB secondary index entry ends with the row's primary key, so `idx_email` physically holds `email` and `id`. Both selected columns are in the index, the clustered index is never visited, and `Extra` reports `Using index`. Adding `name` to the select list breaks this, because `name` exists only in the clustered index.
  • In MySQL, how can you tell from EXPLAIN that the optimizer used a primary key column appended to a secondary index?
    Compare `key_len` and `ref` with the index definition. If `key` names a single-column secondary index but `key_len` covers more bytes than that column and `ref` lists two values such as `const,const`, the optimizer is using a primary key column as an extra key part. Turning `use_index_extensions` off in `optimizer_switch` for the session and re-running EXPLAIN confirms it.
  • In MySQL with InnoDB, what happens to secondary indexes when an UPDATE changes a row's primary key value?
    The row moves to its new position in the clustered index, and every secondary index entry for that row must change too, because each one embeds the old primary key. An UPDATE of an indexed non-key column touches only the indexes containing that column; a primary key change touches all of them.

A library catalogue card that records a book's call number rather than its shelf position: when books are shuffled along the shelves the cards stay valid, and the call number on the card can answer some questions without fetching the book.

  • InnoDB secondary indexes store a physical row address
  • A primary key column must be listed in an index to be covered
  • Primary key width only affects the clustered index
  • use_index_extensions is off by default and must be enabled
  • A page split forces every secondary index to be updated