Backend & Node.js · APIs, data and failure

How do database indexes work and when can they hurt?

Mediumindexessqlquery performanceUpdated Oct 2026
Quiz this track

Short answer

An index is an auxiliary data structure, usually a B-tree, that lets the database find rows without scanning the whole table. It speeds reads but costs storage and makes writes slower because every index must be maintained.

A B-tree keeps keys sorted, so the database can seek to a range in logarithmic time instead of scanning every row. The query planner chooses an index based on statistics and estimated cost. An index only helps when the query predicate matches its columns and ordering.

sql
CREATE INDEX idx_orders_user_created
ON orders (user_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, total_cents
FROM orders
WHERE user_id = 42
ORDER BY created_at DESC
LIMIT 20;
The composite index matches the filter and sort order. EXPLAIN shows whether the planner uses it.

Rules and gotchas

  • A composite index follows the leftmost-prefix rule
  • Ordering matters: an index on user_id, created_at serves queries filtering by user_id and sorting by created_at
  • A covering index includes all selected columns and can avoid a table lookup
  • Low-selectivity columns, such as a boolean, are often poor single-column indexes
  • Wrapping a column in a function can prevent index use unless a matching expression index exists
  • Every index adds write cost, storage and vacuum or maintenance work

Index the access patterns you actually run, then verify with EXPLAIN and real data. A query that looks indexed can still scan because types differ, statistics are stale or the planner estimates a sequential scan as cheaper. Adding an index to every column is a common overcorrection.

Indexes on foreign keys are not automatic in every database. Missing one can turn a delete or join into a full scan and cause lock contention.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the leftmost-prefix rule?
  2. 2What is a covering index?
  3. 3Why might the planner ignore an existing index?
  4. 4Why does an index slow down writes?

Say it in the interview

An index is a sorted structure that lets the database seek to matching rows instead of scanning the table. Composite indexes help only when the query uses the leading columns in the right order, and a covering index can avoid touching the table. The cost is storage and slower writes, so I index real query patterns and confirm with EXPLAIN rather than indexing every column.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Backend & Node.js mock interview and get scored feedback on depth, clarity and confidence.