Question presented to candidate:
"What is a database index, and how does it actually make a query faster? Walk me through what the database does for WHERE email = ... with and without one, and tell me what an index costs."
What a strong answer should cover:
- An index is a separate, sorted data structure (by default a B-tree) that maps column values to the location of the matching rows, so the engine can jump to them instead of reading the whole table
- Without an index the engine does a full table scan (SQLite
SCAN, PostgreSQLSeq Scan), reading every row; with one it does a search (SEARCH ... USING INDEX,Index Scan) in a few page reads, O(log n) - Indexes also serve
ORDER BY, range conditions, joins andMIN/MAXbecause the entries are kept in order - Costs: extra disk space, slower
INSERT/UPDATE/DELETE(every index is maintained on every write), and memory pressure - When an index is not used: a function or expression on the column, a leading-wildcard
LIKE, low selectivity (most of the table matches), or a missing leading column of a composite index; prove it withEXPLAIN
Code / implementation expected: Optional β CREATE INDEX and an EXPLAIN / EXPLAIN QUERY PLAN before and after.
Schema used by the examples: