Question presented to candidate: "What is a covering index? Give me an example of a query that a covering index helps, and explain why it is faster than an ordinary index on the same column."
What a strong answer should cover:
- A covering index is not a special index type: it is an index that contains every column a particular query needs (filter, join, sort and select list), so the engine answers that query from the index alone and never visits the table rows
- Why it is faster: an ordinary index finds the matching keys, then does one extra lookup per row into the table; a covering index removes that lookup, which on a large table is the random I/O that dominates the cost
- How to build one: put the filter columns in the key in the right order, then add the selected columns either as trailing key columns or as non-key payload with
INCLUDE(PostgreSQL 11+, SQL Server); SQLite and MySQL have noINCLUDE, so you append them to the key - How to prove it: SQLite says
USING COVERING INDEXinEXPLAIN QUERY PLAN, PostgreSQL saysIndex Only Scan(andHeap Fetches), MySQL saysUsing indexin theExtracolumn - Engine details: in SQLite and InnoDB the row id or primary key is stored in every secondary index, so it is covered for free; in PostgreSQL an Index Only Scan still checks the visibility map and may fetch heap pages
- Trade-offs: a wider index is bigger, slower to write and needs maintaining; cover the few hot queries, not every query
Code / implementation expected: Optional β an index, the query it covers, and the plan line that proves the table was not read.
Schema used by the examples: