Question presented to candidate: "We have an index on orders (customer_id, status, created_at). Which of these queries can use it, and how well: filter on customer_id; on customer_id and status; on status alone; on customer_id with a date range; and 'customer 10, paid, newest first'? If you could rebuild the index, how would you choose the column order?"
What a strong answer should cover:
- A composite B-tree index is sorted by the first column, then by the second within equal first values, and so on, like a phone book sorted by surname then first name
- The leftmost-prefix rule: the index can be searched on any leading prefix (
a,a,b,a,b,c); skipping the first column usually means a full scan of the table or of the index - Equality columns first, then one range column; columns after the first range can no longer narrow the search, they only filter
- The index order also serves
ORDER BY(including backwards scans); mixed directions need matchingASC/DESCin the index - Engine details: skip scan (Oracle, MySQL 8.0.13+, SQLite with statistics, PostgreSQL 18) can use a missing leading column only when it has few distinct values; PostgreSQL 16 cannot. "Most selective column first" is a myth when all columns are compared with
=
Clarifying questions expected:
- Which queries run most often, and which use equality versus ranges on each column?
- Do the queries also sort or paginate, and in which direction?
- Which database and version (skip-scan support differs)?
Code / implementation expected: Optional โ EXPLAIN output for each query shape, showing which columns become seek conditions.
Schema used by the examples: