Skip to main content

Module 3: Databases

Indexing & B-Trees

How database indexes and B-Trees make lookups fast — primary vs secondary indexes, composite keys, covering indexes, and write/storage trade-offs.

Without indexes, finding a row means scanning the table. B-Tree-style indexes keep keys ordered so the engine can dive logarithmically — fast reads, with a real cost on writes and storage.

What you will learn

  • Explain why indexes speed point lookups and range scans
  • Describe B-Tree fanout and why trees stay shallow on disk
  • Contrast primary/clustered vs secondary indexes
  • Design composite indexes that match real WHERE/JOIN/ORDER BY clauses
  • State write amplification and over-indexing risks
B-Tree with a root, two internal nodes, and four ordered leaves.
High fanout keeps the tree short, so a point lookup touches few pages.

Why indexes exist

  • A table scan reads every row. Indexes are side data structures that locate matching rows with far fewer I/Os.
  • Speed selective filters: WHERE user_id = ? or email = ?
  • Support joins by finding matching keys quickly
  • Help ORDER BY / GROUP BY when the index order matches
  • Enforce uniqueness (unique indexes / primary keys)
  • Trade-off: extra storage and slower inserts/updates/deletes

Primary vs secondary indexes

  • Not all indexes are equal. Know what stores the row vs what points to it.
  • Primary key uniquely identifies a row; many engines cluster row data around it
  • Clustered index — row data ordered by the key (common for PK in some databases)
  • Secondary index — maps indexed column(s) → row pointer / primary key
  • Lookup via secondary index may need a second fetch of the full row (bookmark lookup)
  • Heap + indexes vs clustered designs differ by engine — describe the idea, not only vendor names

B-Tree intuition

  • Most OLTP indexes are B-Tree-like (B+Tree variants). The interview need is structure and I/O cost, not code.
  • Balanced tree: every leaf is at a similar depth
  • High fanout — many keys per page/node because disk pages are large
  • Shallow height ⇒ few disk reads even for millions/billions of keys
  • Internal nodes guide the search; leaves hold keys (and pointers/row data)
  • Leaves are often linked for efficient range scans

Point lookup vs range scan

  • B-Trees shine at both equality and ordered ranges — that is why they dominate secondary indexes.
  • Point lookup: descend root → leaf to one key
  • Range scan: find the first key, then walk ordered leaves
  • Prefix queries (email LIKE "alice%") can use an index; leading-wildcard LIKE cannot
  • Hash indexes are strong for equality but do not support ranges/order

Composite indexes

  • Column order in a multi-column index is a design choice, not decoration.
  • Index (a, b, c) helps filters that use a left-hand prefix: a, a+b, a+b+c
  • A query filtering only b usually cannot use (a, b, c) efficiently
  • Put equality columns first, then range columns — match the query shape
  • ORDER BY can ride an index if sort order matches the index direction
  • One well-chosen composite beats three overlapping single-column indexes

Covering indexes

  • If the index already contains every column the query needs, the engine can skip the heap/clustered lookup.
  • Covering index = index-only scan for that query
  • Faster reads; larger index; more write cost
  • Useful for hot read paths with a small projected column set
  • Do not cover everything — that recreates the table inside the index

Write & storage costs

  • Every index is another structure that must stay correct on every write.
  • INSERT/UPDATE/DELETE may maintain each affected index (write amplification)
  • Page splits on full leaf pages add I/O and fragmentation over time
  • More indexes ⇒ more disk/SSD space and buffer-pool pressure
  • Bulk loads often drop/rebuild secondary indexes for speed
  • Over-indexing is a common production foot-gun

Selectivity and when not to index

  • An index helps when it narrows the result a lot. Low-selectivity columns often disappoint.
  • High selectivity (email, UUID, order_id) — strong index candidates
  • Low selectivity (boolean is_active alone) — often not worth a solo index
  • Tiny tables may scan faster than index + lookup overhead
  • Functions on columns (LOWER(email)) can disable index use unless you index the expression
  • Always check the real query plan — intuition can be wrong

Related structures (brief)

  • Mention siblings only to show you know when B-Trees are not the answer.
  • Hash index — equality lookups; no ranges
  • Bitmap index — analytics / low-cardinality columns in warehouses
  • Full-text / inverted index — search documents and tokens
  • LSM-trees — write-optimized storage engines; still expose ordered reads via structures on disk
  • In system design, default OLTP secondary index answer remains B-Tree-like

Common mistakes

  • These answers sound confident but lose points.
  • Indexing every column “just in case”
  • Wrong composite order for the actual WHERE clause
  • Expecting an index to help leading-wildcard LIKE
  • Ignoring write latency when adding five indexes to a hot table
  • Confusing primary-key clustering with “no need for any other indexes”

Interview framing

  • Use this order when a design touches the database read path.
  • Name the query pattern: point lookup, range, join, or sort
  • Propose the minimal index (often one composite) that matches it
  • Explain B-Tree seek + optional row fetch in one breath
  • Call out write/storage cost and what you will not index
  • Say how you would verify: EXPLAIN / query plan in production style

Quick revision checklist

  • Index columns in WHERE/JOIN/ORDER BY that matter — not every column.
  • Remember: high fanout ⇒ shallow tree ⇒ few disk seeks.
  • State the leftmost-prefix rule for composite indexes.
  • Call out write amplification and storage cost.
  • Prefer one composite index over many redundant singles.
  • Contrast hash (equality) vs B-Tree (equality + range).

FAQs

Hash index vs B-Tree?

Hash is great for equality lookups; B-Tree supports ranges and ordering. Most OLTP secondary indexes are B-Tree-like.

Does an index always make queries faster?

No. If the predicate matches most rows, a scan can be cheaper. Wrong composites, low selectivity, or tiny tables may not benefit.

Why do indexes slow writes?

Each write must update the table data and every affected index. That means extra I/O, page maintenance, and possible page splits.

What is a covering index?

An index that includes all columns needed by a query so the engine can answer from the index alone without fetching the full row.

How do I choose composite column order?

Match the query: equality filters first (leftmost), then range/sort columns. The index must support a left-hand prefix of the query predicates.

Are primary keys enough?

They speed lookups by primary key. Filters on other columns (email, status+created_at) still need secondary indexes when those queries are hot.

Practice

Learner’s Task

  • Practice out loud for 8–10 minutes using one concrete table and query.
  1. Define a table (e.g. orders) and one hot query with WHERE + ORDER BY.
  2. Propose a composite index; explain leftmost-prefix fit in one sentence.
  3. Walk a B-Tree point lookup: root → leaf → row fetch (if secondary).
  4. List two write/storage costs of that index and one column you refuse to index.
  5. Write a 4-sentence closing: query shape, index choice, B-Tree I/O intuition, and trade-off.