How a Three-Column MySQL Index Serves Different Queries
SQL & DataModel answerLast updated
Analyze how one composite InnoDB index handles three query shapes, covering leftmost-prefix seeks, ordering, range limits, index condition pushdown, and the cost of row lookups.
Context
You maintain a busy MySQL (InnoDB) database. One of its tables is defined as follows:
CREATE TABLE orders (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
tenant_id INT NOT NULL,
status VARCHAR(20) NOT NULL,
created_at TIMESTAMP NOT NULL,
amount DECIMAL(10, 2),
INDEX idx_tenant_status_created (tenant_id, status, created_at)
);
Question
Three queries run against this table:
SELECT * FROM orders WHERE tenant_id = 10 AND status = 'PENDING' ORDER BY created_at DESC;SELECT * FROM orders WHERE tenant_id = 10 AND created_at > '2023-01-01';SELECT tenant_id, status, created_at FROM orders WHERE tenant_id = 10;
For each query, state whether idx_tenant_status_created is used fully, used only in part, or not used at all. Justify each verdict by referring to the leftmost-prefix rule and to the way InnoDB reaches full rows through the clustered (primary key) index.
What your answer should cover
- Why the order of columns inside a composite index matters once a range condition is involved.
- How Query 3, which is covered by the index, differs in cost from a similar query that also selects
amount. - Whether Index Condition Pushdown (ICP) plays a role, and in which of the queries.
- What you would look for in
EXPLAINoutput to confirm your reasoning.
Hints
Hint 1
Picture the index as a sorted list of tuples (tenant_id, status, created_at, id). Ask, for each query, whether the rows you want sit next to each other in that list.
Hint 2
A secondary index leaf holds only its own columns plus the primary key. If a query needs any other column, each matching entry costs an extra descent into the clustered index.
Hint 3
In Query 2 the middle column has no equality condition. Think about what that means for seeking, and whether the remaining condition can still be checked before the row is fetched.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Mental model
An InnoDB secondary index is a B+tree whose leaf entries are sorted tuples:
(tenant_id, status, created_at, id) -- the PK is appended automatically
Entries are ordered by tenant_id, then status within a tenant, then created_at within a status, then id. Two facts explain every verdict.
- Leftmost prefix. The engine can seek only where matching entries are contiguous. That means a prefix of equality columns, optionally followed by one range column. The first range condition is the last column that narrows the seek.
- Clustered lookup. Full rows, including
amount, live only in the primary key tree. A secondary leaf has just the indexed columns plusid. Needing any other column costs one extra PK descent (usually 3-4 page reads) per matching entry.
Query 1: fully used for filtering and ordering
WHERE tenant_id = 10 AND status = 'PENDING' ORDER BY created_at DESC
- Both equality columns form a prefix, so the engine seeks straight to the
(10, 'PENDING')block. All matches are adjacent. - Within that block entries are already sorted by
created_at, so the engine reads it backward and no filesort is needed. In MySQL 8.0,EXPLAINshowstype=refandBackward index scan. SELECT *needsamount, so every matching entry triggers a clustered lookup. If this block is a large fraction of the table, the optimizer may prefer a full scan plus a sort. With aLIMIT, the index path becomes very attractive because the scan can stop early.
Query 2: partially used, helped by ICP
WHERE tenant_id = 10 AND created_at > '2023-01-01'
statushas no condition, so onlytenant_idcan drive the seek (key_lencovers just the INT). Thecreated_atvalues for tenant 10 are sorted separately inside each status group, so they do not form one contiguous range.- The engine therefore scans the whole tenant 10 slice of the index.
- ICP:
created_atis stored in the index entry, so InnoDB can testcreated_at > ...on each entry before fetching the row. Without ICP, every tenant 10 row would be fetched from the PK tree and then filtered by the server layer. With ICP only qualifying entries cause lookups, which can eliminate most random I/O.EXPLAINshowsUsing index condition. - Skip scan (MySQL 8.0.13+) could hop across distinct
statusvalues, but only for covered queries.SELECT *is not covered, so it does not apply. - Fixes: if
statushas few values, addstatus IN (...)so the optimizer builds several tight ranges. If the query is hot, create a dedicated index on(tenant_id, created_at).
Why column order matters for ranges
A range selects a span of keys, and inside that span the later columns are no longer globally sorted. They cannot be used to seek or to provide ordering. So the rule is: equality columns first, then a single range or sort column last.
For tenant_id = ? AND status = ? AND created_at > ?:
| Index | Use |
|---|---|
(tenant_id, status, created_at) | One tight range using all three predicates |
(tenant_id, created_at, status) | Range on created_at; status only filtered via ICP |
Query 3: covering index
SELECT tenant_id, status, created_at FROM orders WHERE tenant_id = 10
Every requested column is in the leaf entry, so the clustered index is never touched. EXPLAIN shows Using index. The work is a sequential scan of densely packed leaf pages, with hundreds of entries per 16 KB page.
Contrast with also selecting amount:
- The covering version reads a few thousand pages for a tenant with a million rows.
- The non-covering version does up to one million PK descents, in index order rather than PK order, which is random I/O whenever pages are not in the buffer pool.
- Past a selectivity threshold (often cited around 20-30% of the table) the optimizer abandons the index for a full scan.
- Fix: extend the index to
(tenant_id, status, created_at, amount). MySQL has noINCLUDEclause, so the extra column becomes a trailing key column, at the cost of a larger index and slower writes.
Complexity
Let N be table size, k the index entries scanned, and m the rows needing a PK lookup.
| Query | Time |
|---|---|
| 1 | O(log N + k log N), no sort |
| 2 | O(log N + k + m log N), ICP shrinks m |
| 3 | O(log N + k) |
The index costs O(N) storage, roughly 30-40 bytes per entry here.
Verifying with EXPLAIN
- Check
keyandkey_lento see how many prefix columns were used for the seek. Using indexmeans covered.Using index conditionmeans ICP.Using filesortmeans the ordering was not satisfied by the index.- Run
ANALYZE TABLEif statistics look stale and the optimizer picks a surprising plan.
Common mistakes
- Claiming Query 2 ignores the index. It uses the
tenant_idprefix and ICP. - Forgetting that
SELECT *defeats covering. - Wrapping an indexed column in a function, such as
DATE(created_at) = ..., which blocks seeking. Use a range on the raw column. - Comparing a VARCHAR column to a number, which forces a conversion and disables the index.
- Mixed sort directions such as
ORDER BY status ASC, created_at DESC, which need a MySQL 8.0 descending index column. - Ignoring low selectivity: a tenant owning most of the table can make a full scan cheaper.