How do database indexes work, and when do they hurt?
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
Interviewers use indexes to test whether you connect query performance to physical storage instead of just syntax. Strong candidates explain page I/O, the leftmost-prefix rule for composite keys, and why the planner might ignore an index. It also probes judgment: knowing when not to add an index is as valuable as knowing how to add one.
Mental model
An index is a sorted B+Tree keyed by column values whose leaves point at rows. Lookups descend O(log n) pages instead of scanning O(n) pages, but every INSERT/UPDATE/DELETE must maintain the tree. Indexes accelerate reads for selective predicates — the first columns of a composite key and covering queries especially — and can slow writes and even reads when selectivity is poor.
Step-by-step solution
Step 1: Full scans read every page
Without an index, SELECT * FROM users WHERE email = ? forces the planner into a sequential scan: read every heap page, test every row, and stop only when the relation ends. Cost scales with table size and row width — ten million rows at roughly one hundred rows per page is about one hundred thousand page reads, and if the table does not fit in the buffer cache, many of those are physical disk I/Os. Watch the animation: the query touches heap page after heap page, and the rows-tested node grows without any bound tied to the predicate. The work is O(n) in pages regardless of how selective the filter is, because the heap has no ordering that helps. An index changes the shape of that work from linear scanning into logarithmic descent, which is the entire reason databases maintain a second copy of the keys.
Step 2: What a B+Tree buys
A B+Tree keeps keys sorted in a shallow, wide tree: the root and internal nodes hold separator keys that route a search, and the leaves hold the actual keys in sorted order, linked sideways for range scans. A three- or four-level tree covers millions of rows because each page fans out to hundreds of children. Searching one email walks root, then internal, then leaf: a handful of page reads instead of tens of thousands. The animation shows that descent — at every node the search key routes down a single branch, so the remaining search space shrinks by fan-out at each level. Insertions and deletions keep the tree balanced through page splits and merges, which is a maintenance cost paid on every write. Range queries are a B+Tree strength: find the first leaf, then follow sibling pointers instead of descending again.
Step 3: Walk an indexed lookup
Put the pipeline together. The query arrives with a predicate, and the planner decides the cheapest access path; with an equality filter on an indexed column it chooses the B+Tree. The search starts at the root page, compares the key against separator values, and follows the single child page that can contain the target. At the leaf page the key is found among sorted entries, and the leaf's row pointer identifies the heap page and slot; a final page read fetches the actual row. That is O(log n) index page reads plus one row fetch, versus O(n) heap reads for a scan. Watch the animation's active node move one step per phase: every arrow is a real page I/O, and there are only a handful of them. Without a covering index, the row fetch is an extra random read — the hidden second cost.
Step 4: Composite keys follow leftmost prefix
A composite index on (last_name, first_name, birth_date) is sorted first by last name, then first name, then birth date — like a phone book. That ordering means the index can serve predicates on last_name, on last_name plus first_name, and on the full key. A query filtering only first_name cannot seek, because equal first names are scattered across every last-name range: the planner must scan the whole index or fall back to the heap. Range conditions stop the prefix too — last_name equality plus a birth_date range can locate the last-name range but cannot use birth_date as a search key because first_name intervenes. Put equality columns first and range columns last. Watch the animation: one query seeks straight to a leaf, while the other has no anchor and touches every leaf before any heap rows.
sqlCREATE INDEX idx_users_name ON users (last_name, first_name, birth_date); -- Uses the index: leftmost prefix SELECT * FROM users WHERE last_name = 'Patel'; -- Uses the index: both prefix columns SELECT * FROM users WHERE last_name = 'Patel' AND first_name = 'Ana'; -- Cannot seek: first_name is not a leftmost column SELECT * FROM users WHERE first_name = 'Ana';
Step 5: When an index hurts
Indexes are not free. Every write must update each index, which means more page splits, more buffer-pool pressure, and a slower INSERT/UPDATE path — write amplification. A low-cardinality column such as status rarely helps: when a query matches a large fraction of the table, the planner estimates that a sequential scan costs fewer page reads than bouncing between index and heap pages, and it ignores the index. Non-covering indexes pay an extra random row fetch per match, so returning most of the table through an index can be slower than scanning it. When the index already contains every needed column and the visibility map marks the pages all-visible, that fetch disappears — an index-only scan. The judgment answer is to index for the queries you actually run, verify with EXPLAIN ANALYZE (below), and remove indexes whose write cost outweighs their read wins.
sql-- Low selectivity: the planner prefers the heap EXPLAIN ANALYZE SELECT * FROM users WHERE status = 'active'; -- Seq Scan on users (rows=98000) Filter: (status = 'active') -- High selectivity: the index wins EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'ada@example.com'; -- Index Scan using users_email_idx on users (rows=1)
Edge cases & traps
- Leading wildcards (LIKE '%foo') cannot use a B+Tree: rewrite as a prefix LIKE 'foo%' or add a trigram/GIN index.
- Wrapping the indexed column in a function (WHERE lower(email) = ?) disables the index: index the expression or normalize on write.
- Adding an index for every foreign key without checking usage taxes every write — keep only the indexes that queries actually exercise.
- Forgetting that a non-covering index adds a random row fetch per match: extend the index to cover selected columns or accept the scan.
- Assuming an index is always faster: for low-selectivity predicates such as status = 'active', a sequential scan is often cheaper.