← Back to System Design, page 1

system-design-0013 · Medium fresher

How does a database index work, and how do composite indexes and the leftmost-prefix rule affect queries?

An index is a separate sorted data structure, usually a B-tree, that maps column values to row locations so the database can find rows without scanning the whole table. A composite index on (a, b) is sorted by a then b, so it helps queries that filter on a, or on a and b, but not on b alone. Indexes speed reads and slow writes and use storage.

Full answer

The idea

Without an index, finding a student's marks means reading every row (a full table scan). An index works like the index at the back of a textbook: a sorted list of terms with page numbers, so you jump straight to the right page.

How a B-tree index works

Most relational databases use B-tree (B+ tree) indexes. The tree is shallow and wide: each node holds hundreds of keys, so even a billion rows need only about 4 or 5 levels. A lookup walks from the root to a leaf in a few page reads, then follows the pointer to the row. Because leaves are sorted and linked, range queries (score BETWEEN 60 AND 80) and ORDER BY on the indexed column are also fast.

Hash indexes exist too. They are fast for exact matches but cannot do ranges or sorting.

Composite indexes and the leftmost prefix

An index on (student_id, exam_date) is sorted by student_id first, then by exam_date within each student. It can serve:

  • WHERE student_id = 42
  • WHERE student_id = 42 AND exam_date >= '2026-01-01'

It cannot efficiently serve WHERE exam_date >= '2026-01-01' alone, just as a phone book sorted by surname then first name does not help you find everyone named "Priya".

You can check this with the query plan. This snippet was run with Python 3.13 and SQLite 3.46.1:

python
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE marks (student_id INTEGER, subject TEXT, exam_date TEXT, score INTEGER)")
q = "SELECT score FROM marks WHERE student_id = 42 AND exam_date >= '2026-01-01'"
print(db.execute("EXPLAIN QUERY PLAN " + q).fetchall()[0][3])
db.execute("CREATE INDEX idx_marks_student_date ON marks (student_id, exam_date)")
print(db.execute("EXPLAIN QUERY PLAN " + q).fetchall()[0][3])
q2 = "SELECT score FROM marks WHERE exam_date >= '2026-01-01'"
print(db.execute("EXPLAIN QUERY PLAN " + q2).fetchall()[0][3])

Output:

SCAN marks SEARCH marks USING INDEX idx_marks_student_date (student_id=? AND exam_date>?) SCAN marks

Put equality columns first and the range column last.

Costs

  • Every insert, update and delete must also update each index, so heavy indexing slows writes.
  • Indexes take disk and memory.
  • Low-selectivity columns (a boolean is_active) rarely help on their own.
  • Functions on the column (WHERE LOWER(email) = ...) skip a plain index unless you create an expression index.

A covering index includes all columns the query needs, so the database answers from the index without reading the table.

By level

Fresher: Explain what an index is with an analogy, why it avoids a full scan, and that it slows writes a little. A fresher should know that an index speeds reads but slows writes.

Mid: Explain B-tree structure, composite index ordering, covering indexes, selectivity and reading a query plan. Expect a correct composite index for a given query.

Senior: Discuss index design for a real workload, write amplification, index bloat and maintenance, online index creation, and when secondary indexes in a sharded database become a cross-shard problem. Expect awareness of the cost of secondary indexes once the data is sharded.

Key points

  • An index is a sorted structure (usually a B+ tree) pointing to rows
  • B-trees serve equality, range and ORDER BY; hash indexes only equality
  • Composite indexes follow the leftmost-prefix rule
  • Put equality columns before range columns
  • Indexes cost write speed and storage

Common mistakes

  • Indexing every column
  • Expecting an index on (a, b) to help a filter on b alone
  • Wrapping the column in a function and losing the index
  • Not checking the query plan

Follow-ups

  • What is a covering index?
  • Why might the optimiser ignore an index that exists?
  • How do indexes behave on a column with only two distinct values?

Tips

  • Use the textbook index or phone book analogy, then go to B-trees
  • Show a query plan before and after
  • Mention write cost without being asked

Evaluation rubric

  • Correct explanation of index structure
  • Correct leftmost-prefix reasoning
  • Mentions write and storage costs
  • Knows how to verify with a query plan