Composite and Covering Indexes
In MySQL, explain composite indexes and the leftmost-prefix rule, and what a covering index is. Given an index on (a, b, c), which of these can use it: where a = 1 and b = 2, where b = 2, where a = 1 and c = 3, where a > 1 and b = 2? And why not index every column?
Answer out loud in under a minute: a definition, one concrete example, and one pitfall or trade-off.
Hints
Hint 1
Picture a phone book sorted by surname, then first name, then city, and try to look someone up by first name alone.
Solution
Show the approach
The short version
A composite index is one B+ tree whose entries are sorted by the first column, then the second within equal values of the first, and so on. The tree can be searched only along that order, so a query can use the index for a leftmost prefix of its columns: equality conditions extend the usable prefix, and the first range condition is the last column that narrows the search. In InnoDB a secondary index stores the primary key with each entry; a query that needs other columns goes back to the clustered index for each row. A covering index contains every column the query reads, so that second lookup is skipped.
Example
With (a, b, c): a = 1 and b = 2 seeks on both columns. b = 2 alone cannot seek, because b is only ordered within each value of a. a = 1 and c = 3 seeks on a and then filters on c inside the index, without using c to narrow the range. a > 1 and b = 2 uses the range on a; b is checked per entry. And select b from t where a = 1 is covered: EXPLAIN shows Using index.
Pitfall
Every index is written on every insert, update and delete, takes space and competes for the buffer pool, and gives the optimizer more ways to choose badly. Design indexes from the actual queries: equality columns first, then the range or sort column, and widen to cover only for hot queries. Wrapping an indexed column in a function, an implicit type conversion, or a leading wildcard in LIKE stops the index from being used.
Assistant
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.