Indexing and Query Performance

Learn how B+ tree and hash indexes work, clustered vs non-clustered indexes, composite index ordering, and how to read a query plan.

Intermediate · about 5 hours · difficulty 3/5

Learn first: SQL for Interviews, Binary Search Trees

An index is a data structure that lets the database find rows without scanning the whole table. Indexing questions test whether you can connect DSA knowledge (trees, hashing, binary search) to real systems.

How indexes work

  • Most relational indexes are B+ trees: balanced, very wide nodes sized to disk pages, with all data pointers in the leaves and leaves linked for fast range scans. Height stays around 3 or 4 even for millions of rows.
  • Why not a binary search tree? Each node visit is a disk read, so fewer, wider nodes win.
  • Hash indexes give O(1) equality lookups but cannot do ranges or sorting.

Kinds of indexes

  • Clustered (primary): table rows are stored in index order; only one per table (InnoDB clusters by primary key).
  • Non-clustered (secondary): a separate structure pointing to rows; a lookup may need an extra hop.
  • Composite index on (a, b): usable for filters on a or a and b, but not b alone. This leftmost prefix rule is a classic question.
  • Covering index: contains every column a query needs, so the table is never touched.
  • Dense vs sparse indexes (exam theory).

When indexes hurt

  • Every insert, update and delete must also update each index, so write-heavy tables should have few.
  • Low-selectivity columns (like a boolean) rarely benefit.
  • Functions on a column (WHERE LOWER(email) = ...) or leading wildcards (LIKE '%abc') usually prevent index use.

Reading query plans

Use EXPLAIN (and EXPLAIN ANALYZE) to see sequential scans vs index scans, join algorithms (nested loop, hash join, merge join) and estimated vs actual rows. Also avoid the N+1 query problem in application code.

Good enough to move on: you can explain why B+ trees suit disks, predict whether a composite index will be used, and speed up a slow query with EXPLAIN.

Key concepts

  • B+ tree indexes
  • Hash indexes
  • Clustered vs non-clustered
  • Composite indexes and leftmost prefix
  • Covering indexes
  • Index write costs and selectivity
  • EXPLAIN and query plans
  • Join algorithms

Mini project

Generate a 1 million row orders table in PostgreSQL, time five common queries without indexes, add single, composite and covering indexes one at a time, and record the EXPLAIN ANALYZE output and speedup for each.

Check yourself

Given an index on (city, age), which of these can use it: WHERE city = 'Pune', WHERE age = 21, WHERE city = 'Pune' AND age > 21? Why?

Free resources