Course map

Topic 064 / Core

Indexing: B-tree, hash and LSM-tree; composite, covering and partial indexes

Chapter 5.3 · Indexing, Search, and Query Performance

What and why

A table scan reads every row; a scan over a sorted or hashed copy of just the relevant columns can skip almost all of them. An index is such a copy, traded for extra storage and write cost, chosen for the shape of the lookup it must serve. Builds on: → 2 (data structures and algorithms: hash maps, trees, tries, heaps, queues).

Diagram

Two-level B-tree index lookup A root node holding keys 30 and 60 branches to three leaf nodes: 10 and 20, 40 and 50, and 70 and 80. Looking up key 42: 42 is greater than 30 and less than or equal to 60, so the search descends to the middle leaf; there 42 falls between 40 and 50, matching that leaf. Two comparisons reach the leaf instead of scanning every key. lookup key: 42 [ 30 | 60 ] [10|20] [40|50] [70|80] ≤ 30 30 < 42 ≤ 60 > 60 42 is between 40 and 50 → match Two comparisons reach the leaf instead of scanning every key.
To find 42: 42 > 30 and ≤ 60, so descend to the middle child; 42 sits between 40 and 50, so descend to that leaf. Two comparisons reach the leaf instead of scanning every key.
Text version of this diagram

A tiny two-level B-tree:

                [ 30 | 60 ]
               /     |     \
        [10|20]  [40|50]  [70|80]

To find 42: 42 > 30 and ≤ 60 → go to the middle child; 42 is between 40 and 50 → descend there. Two comparisons reach the leaf instead of scanning every key.

How it works

  1. B-tree: sorted, balanced, O(log n) search; supports range scans and prefix matches because neighboring keys sit near each other. The default for most relational indexes.
  2. Hash index: hashes the key to a bucket; O(1) exact-match lookup, no ordering — can't serve a range query at all.
  3. LSM-tree: writes buffer in memory, flush as sorted immutable files; background compaction merges files and discards overwritten/deleted entries; writes are cheap (sequential append), reads may check several files (engine view → 67).
  4. Composite index: a concatenation of columns, usable for a query only if the query's filter matches a left prefix of the column order.
  5. Covering index: includes every column a query needs, so the engine never touches the table row ("index-only scan").
  6. Partial index: indexes only rows matching a predicate — smaller, cheaper, when most rows are irrelevant to the query it serves.

Practical example

CREATE INDEX idx_order_customer_date ON "order" (customer_id, created_at);           -- composite
CREATE INDEX idx_order_cover ON "order" (customer_id) INCLUDE (status);             -- covering
CREATE INDEX idx_order_pending ON "order" (customer_id) WHERE status = 'pending';    -- partial

idx_order_customer_date serves WHERE customer_id = ? and WHERE customer_id = ? AND created_at > ?, but not WHERE created_at > ? alone — that filter isn't a left prefix.

When to use it

  • Use when: a column is filtered, joined, or ordered on, and is selective enough to skip most of the table.
  • Avoid when: the column has very low cardinality (a boolean on a small table) or the table is write-heavy with little matching read traffic — every index is maintained on every write.
  • Failure scenarios: an index exists but the query wraps the column in a function (WHERE lower(email) = ? against a plain index on email) so the planner can't use it; a composite index built in the wrong column order for the actual queries.
  • Simpler alternative: for a small table, a sequential scan may already be fast enough — don't index before measuring.

Practice

(mechanism — trace by hand, then verify; 20–30 min, lab Postgres). First, trace the B-tree lookup above by hand for key 15 and key 65. Then in the lab, create a composite index on two columns, run EXPLAIN on a query that uses the leading column and one that uses only the trailing column, and confirm the index is used in the first case and not the second. Done when you predict index use correctly before running EXPLAIN.

Shared lab setup

Key takeaway

Match the index structure (B-tree, hash, LSM) and shape (composite, covering, partial) to the actual query, not every column that might someday be filtered on. Done when you can: read a composite index definition and say which queries it does and doesn't serve. Used next in → 65, 66; engine internals → 67.

References

Kleppmann and Riccomini, Designing Data-Intensive Applications — see references.md.

Source directory

Search the guide