Why SELECT * Is the Enemy of a Covering Index: The Three-Gate Chain of MySQL Index Optimization
Why SELECT * Is the Natural Enemy of the Covering Index?
Author: 斯维赤
Tags: Backend, Java, MySQL
★
Recommended audience: Backend engineers who can build composite indexes but can't figure out why they're sometimes fast and sometimes slow, and students who can only recite the definition of "index condition pushdown" in interviews.
One-sentence guide: Leftmost prefix, covering index, index condition pushdown — these look like three separate terms, but they are actually three gates on the same chain: whether the index can be used, whether a row lookup is needed after using it, and whether you can reduce the number of lookups when one is unavoidable. Put them back on this chain and each one's job becomes clear.
01 · One index, three SQL queries, speed differences of an order of magnitude
Here's a scenario I actually tuned. A user table has a composite index:
CREATE TABLE user (
id BIGINT PRIMARY KEY,
name VARCHAR(32),
age INT,
city VARCHAR(32),
KEY idx_name_age_city (name, age, city)
);
Three queries all "use" this index:
SELECT name, age FROM user WHERE name='张';
SELECT * FROM user WHERE name='张' AND age=20;
SELECT * FROM user WHERE age=20;
The first is millisecond-level, the second is acceptable, the third does a full table scan. Many people's first reaction is "the index failed", but actually each of these three things governs a different part, and mixing them together will never make sense.
My understanding is: the leftmost prefix determines whether the index is usable, the covering index determines whether a row lookup is needed, and index condition pushdown determines how many rows can be filtered out before the lookup. These three concepts are a progressive chain of IO savings, not three parallel technical points.
To understand the chain, you first need to see what an InnoDB index looks like.
02 · The foundation: clustered index, secondary index, and "row lookup"
InnoDB has two kinds of indexes, and their leaf nodes hold different things:
- Clustered index (usually the primary key) — leaf nodes store the entire row directly. Find the primary key, and you've found the row.
- Secondary index (ordinary index) — leaf nodes only store "index column values + the corresponding primary key value". It doesn't store the full row.
So when you query through a secondary index, the process is two steps: first find the primary key value in the secondary index tree, then use that primary key to fetch the full row from the clustered index tree. That second step is called row lookup (回表).
Secondary index tree (name -> primary key)
name='张' -> id=15
|
| Row lookup: use id to fetch full row from clustered index
v
Clustered index tree (id -> full row)
id=15 -> complete row data
A row lookup is a random IO and the main culprit for slow queries. Keep that in mind, because all three concepts revolve around one goal: how to reduce row lookups, even eliminate them.
03 · Leftmost prefix: solving "the index is built but not used"
The composite index idx_name_age_city is sorted in the B+ tree as (name, age, city): first by name, then by age when names match, then by city. Like a phone book sorted by last name, then first name.
This sort order determines that: a query must start from the leftmost column and match consecutively to the right to use the index.
-- Full match: name / age / city all used for positioning
WHERE name='张' AND age=20 AND city='北京'
-- Only name matches; city can't be used (age is skipped in the middle)
WHERE name='张' AND city='北京'
-- Total failure: the leftmost column name is absent
WHERE age=20
The second example deserves special note: the city column is not completely useless — it will be picked up by "index condition pushdown" for filtering (see section 05), but it can't be used for positioning the scan range in the index tree. These are two different roles, don't confuse them.
Another common pitfall is range conditions:
-- age is a range condition, so the columns to its right can't be used for positioning
WHERE name='张' AND age > 18 AND city='北京'
So there's an empirical rule for building composite indexes: put equality columns first, range columns last. That way, even if the columns to the right of a range column can't be used, at least all equality columns benefit.
The leftmost prefix solves the problem of "the index is designed correctly, and the SQL conditions are in the right order, but the index actually takes effect". It governs the entry gate.
04 · Covering index: solving "used the index, but still had to do a row lookup"
Now look at the first millisecond query:
SELECT name, age FROM user WHERE name='张';
It's fast not because the condition is simple, but because the columns to be queried (name, age) happen to be both inside the composite index. The secondary index's leaf node already has name, age, and primary key id, so the engine can return results directly from the index without going to the clustered index.
That's a covering index — the query columns are "covered" by the index, and the row lookup is saved entirely. When EXPLAIN shows Extra: Using index, that's it in action.
Compare:
-- Row lookup: SELECT * wants all columns, which the index doesn't have
SELECT * FROM user WHERE name='张';
-- Covered: name, age are both in idx_name_age_city
SELECT name, age FROM user WHERE name='张';
SELECT * is the natural enemy of the covering index. Writing SELECT * means you're declaring "I want all columns", and a composite index can't cover all columns (unless you put every column in the table into the index, which defeats the purpose), so a row lookup is inevitable.
But covering indexes have their own cost to weigh. I've seen people stuff seven or eight columns into an index just to cover a query, and the index file bloats to larger than the data itself, slowing down all writes and filling the buffer pool with index pages. My rule: only cover 2 to 3 key columns for the highest-frequency queries, don't be greedy.
The covering index solves the problem of "now that the index is used, can we avoid the row lookup".
05 · Index condition pushdown: solving "did the row lookup and found it was wasted"
Index Condition Pushdown (ICP), added in MySQL 5.6, is something many people can only recite as "push the condition down to the storage engine" without knowing what it saves. Look at this query:
SELECT * FROM user
WHERE name LIKE '张%' AND age=20;
The index is idx_name_age_city, name is leftmost and can locate; age is the second column, but because name uses a LIKE prefix match (a range-ish condition), age can't be used to locate the scan range.
Without ICP:
- The storage engine finds all records with name like '张%' in the index tree, suppose 100 records, and takes their primary keys.
- It does a row lookup for each of those 100 rows, fetching the full data.
- The server layer then filters with age=20, leaving only 5 rows out of 100.
The problem: those 95 row lookups were wasted. The condition age=20, even though age is in the index, is only checked after the row lookup.
With ICP: the storage engine scans the index for records with name like '张%' and, on the fly, uses the age value in the index to check age=20, skipping those that don't match and not doing a row lookup. Only the 5 matching rows get a row lookup. The row lookups drop from 100 to 5.
When EXPLAIN shows Extra: Using index condition, that's ICP working.
There's an easy-to-confuse point: ICP reduces the number of row lookups, not the number of index rows scanned. Those 100 index entries with name '张%' still have to be read one by one; ICP just avoids doing a row lookup for each one.
Its boundaries are clear too: it only works for secondary indexes, and the pushed-down condition must be evaluable using columns in the index — if a condition uses a column not in the index, a row lookup is still required.
Index condition pushdown solves the problem of "when a row lookup is unavoidable, can we filter first before the lookup".
06 · How the three work together, plus an EXPLAIN quick reference
Put the three concepts back on the chain, and the tuning order becomes clear:
- Gate 1, leftmost prefix — Do the conditions start from the leftmost column and match consecutively? If not, fix the SQL or rebuild the index order first; the next two gates are moot.
- Gate 2, covering index — Can all the columns that high-frequency queries want fit in the index? If yes, the row lookup is saved entirely.
- Gate 3, index condition pushdown — In cases where
SELECT *or a row lookup is unavoidable, does the index contain filterable columns so ICP can cut down the number of lookups?
When debugging, EXPLAIN lets you see at a glance which gate fails:
- key = NULL — gate 1 failed; the index wasn't used at all
- type = ref / range — the index was used; gate 1 passed
- Extra = Using index — gate 2 passed; covering index, no row lookup
- Extra = Using index condition — gate 3 passed; ICP is reducing row lookups
- Extra = Using where — the server layer filtered again after the row lookup; see if covering index or ICP can optimize it away
One-line memory aid: leftmost prefix governs "can you get in the door", covering index governs "can you avoid going home", index condition pushdown governs "fewer detours on the way".
07 · Three-sentence summary
- The three concepts are three gates on the same IO-saving chain: leftmost prefix decides whether the index is usable, covering index decides whether a row lookup is needed, and index condition pushdown decides how much can be filtered before the lookup.
- Leftmost prefix requires consecutive matching from the leftmost column of a composite index, with equality columns first and range columns last; covering index relies on index columns "containing" the query columns to avoid row lookups, and
SELECT *defeats it. - Index condition pushdown filters conditions that can be evaluated from index columns at the engine layer first, reducing the number of row lookups but not the number of scanned rows; looking at EXPLAIN's key / type / Extra tells you which gate is stuck.
Closing words
If you found this useful, please do two things:
- Click "Like" + "Recommend" (or share)
- Follow "斯维赤" — Java practice, database pitfalls, development tools, continuously updated.
See you next time.
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
This article's framing of linking the three concepts into an "IO-saving chain" is spot on. Let me add four points that matter more in practice: 1) The most valuable benefit of a covering index is often not avoiding the table lookup but avoiding filesort. Putting the sort column of `ORDER BY create_time DESC LIMIT 20` into the index (index order = sort order) can eliminate both the table lookup and filesort at once. This yields much greater gains than tuning ICP, but few people think about it when designing indexes. 2) The cost of `SELECT *` on a wide table is not limited to table lookup. If there are TEXT/BLOB columns, InnoDB stores large fields on off-page overflow pages, requiring an additional page read—and this happens **for each row**. At this point, the difference between "one table lookup" and "table lookup + N overflow page reads" is an order of magnitude, and `EXPLAIN` cannot show that at all. 3) `type=ref` does not imply a small number of rows. `rows` is estimated from statistics; when sampling is inaccurate, the estimate can be off by orders of magnitude. To judge the actual cost, use `EXPLAIN ANALYZE` (8.0.18+), which gives the actual row count and actual execution time. I got burned once: `rows=3` actually scanned 40,000 rows because the statistics hadn't been updated for a week. 4) `Using index` and `Using index condition` can appear together (`Using index; Using index condition`); they are not mutually exclusive. I'd suggest adding to the article's quick-reference table: seeing both together means covering index and index condition pushdown are both in effect—that's the best case. Finally, a trap related to the leftmost prefix in the article: in `WHERE name LIKE '张%' AND age = 20`, `age` cannot be used for positioning, but if you write `age = 20 AND name LIKE '张%'`, the optimizer will still pick the correct index—**the order does not affect whether it can be used, only how clear it is to read**. What truly matters is "which column can form a contiguous leftmost prefix."