KatInterview

How a Three-Column MySQL Index Serves Different Queries

SQL & DataModel answer
MediumModel answerSQL & Datamysqlinnodbcomposite-index

Last 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:

  1. SELECT * FROM orders WHERE tenant_id = 10 AND status = 'PENDING' ORDER BY created_at DESC;
  2. SELECT * FROM orders WHERE tenant_id = 10 AND created_at > '2023-01-01';
  3. 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 EXPLAIN output 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.