Skip to main content
08

How do indexes work, and when don't they help?

MediumDatabasesIndexesB-tree

How do database indexes work, and when don't they help?

TL;DR

An index is a separate, sorted data structure (usually a B-tree) that maps column values to row locations, so the database finds rows in O(log n) instead of scanning the whole table. Indexes speed up WHERE, JOIN, ORDER BY and range lookups, but they cost disk space and slow down every write, since each INSERT, UPDATE and DELETE must update each index. They don't help when the query returns a large share of the table, when the indexed column is wrapped in a function, or when the query doesn't match the index's leftmost columns.

Key points

  • Composite index (a, b): works for a, or a and b, but not b alone (the leftmost-prefix rule). Put equality columns first, then the range or sort column.
  • Covering index: includes every column the query needs, so the table isn't touched (an index-only scan; INCLUDE in PostgreSQL).
  • Selectivity: an index on a low-cardinality column (is_active) is rarely used. A partial index (WHERE is_active) can fix that.
  • Index killers: WHERE lower(email) = ... (use an expression index), LIKE '%term' (leading wildcard), and implicit type casts.
  • Other types: hash (equality only), GIN (JSONB, arrays, full-text), GiST (geo), BRIN (huge append-only tables).
  • Check with EXPLAIN ANALYZE that the index is really used.

Example

sql
CREATE INDEX orders_customer_created_idx ON orders (customer_id, created_at DESC);

-- Uses the index for both the filter and the sort
SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;

-- Can't use it efficiently: skips the leftmost column
SELECT * FROM orders WHERE created_at > now() - interval '1 day';

Common follow-ups

  • Clustered vs non-clustered? A clustered index is the table, stored in key order (InnoDB's primary key). Others point back to the row.
  • Why didn't the planner use my index? Low selectivity, stale statistics (ANALYZE), a tiny table, or a non-matching expression.

What interviewers look for

Tip

B-tree and O(log n), the read/write trade-off, the leftmost-prefix rule, and checking with EXPLAIN.

  • Red flag: "add an index on every column."

Was this helpful?

Related questions