Indexes, B-trees and LSM trees
Overview
Without an index, finding one row means reading every row: a full table scan. On a table with 100 million rows that takes seconds or minutes. An index is a separate, sorted structure that points to rows, turning that scan into a few reads. This lesson explains how indexes work, what they cost, and the two storage engine designs behind almost every database.
What an index is
Think of the index at the back of a book: sorted terms with page numbers. A database index is a sorted list of values of one or more columns, each pointing to its row. Because it’s sorted, the database can:
- find an exact value quickly (
WHERE email = ...), - scan a range (
WHERE created_at > ...), - return rows already in order (
ORDER BY created_at), avoiding a sort.
Composite indexes
An index on (city, signup_date) is sorted by city, then by date within each city. It helps:
WHERE city = 'Pune'WHERE city = 'Pune' AND signup_date > '2026-01-01'WHERE city = 'Pune' ORDER BY signup_date
It doesn’t help WHERE signup_date > ... alone, just as a phone book sorted by surname can’t find everyone named “Priya” quickly. Put the column you filter on with equality first.
The cost
Every index must be updated on every insert, update and delete of the indexed columns, and it takes storage and memory. Ten indexes on a busy table can make writes several times slower. Index for the queries you actually run, and remove unused indexes.
Two storage engine designs
B-trees
A B-tree stores keys in fixed-size pages (often 8–16 KB) arranged as a wide, shallow tree. Each page holds hundreds of keys, so even billions of rows need only three or four levels. A lookup reads one page per level, and the top levels are usually cached in memory.
Writes find the right leaf page and modify it in place; if a page fills up, it splits. Used by PostgreSQL, MySQL (InnoDB), SQL Server, Oracle and SQLite.
- Strengths: predictable, fast reads; efficient range scans; mature.
- Weaknesses: random writes to pages all over the disk; page splits; random keys (like UUID v4) scatter inserts and bloat the index.
LSM trees
A log-structured merge tree never updates data in place:
- Writes go to an append-only write-ahead log (for durability) and to a sorted in-memory table, the memtable.
- When the memtable is full, it’s written to disk as an immutable sorted file, an SSTable.
- In the background, compaction merges SSTables, discarding overwritten and deleted values.
Reads check the memtable, then SSTables from newest to oldest. Bloom filters (small probabilistic structures) let the engine skip files that certainly don’t contain the key. Used by Cassandra, ScyllaDB, RocksDB, LevelDB, HBase and Bigtable.
- Strengths: very high write throughput (sequential I/O), good compression.
- Weaknesses: reads may touch several files; compaction uses CPU and disk in the background and can cause latency spikes.
Which when?
| Workload | Prefer |
|---|---|
| Read-heavy transactional apps (users, orders) | B-tree |
| Very write-heavy (logs, metrics, messages, IoT) | LSM |
| Lots of range scans with updates | B-tree |
| Huge datasets with mostly appends | LSM |
You usually choose the engine by choosing the database, so this is mostly a “why” you can explain in an interview: “Cassandra suits the chat message store because its LSM engine handles very high write rates.”
Durability: the write-ahead log
Both designs use a write-ahead log (WAL): every change is appended to a log on disk before it’s applied to the main data structures. After a crash, the database replays the log to recover. The same log is often used to feed replicas (the replication lesson).
Other kinds of index
- Hash indexes: exact lookups only, no ranges.
- Full-text (inverted) indexes: map words to documents (week 6, search).
- Geospatial indexes: R-trees or geohashes for “near me” queries (the ride-sharing case study).
- Partial and covering indexes: index only some rows, or include extra columns so the table isn’t read.
Recap
Indexes are sorted structures that make reads fast and writes slower. Composite indexes work left to right. B-trees update pages in place and offer fast, predictable reads; LSM trees append, flush and compact, offering very fast writes at some read cost. Both rely on a write-ahead log for durability. Index for your real queries and pick the engine that matches your read/write balance.
Pick the indexes and the engine
(a) A users table has 50 million rows. The app runs these queries often: find a user by email; list users in a city sorted by signup date; count users who signed up today. Which indexes would you create? (b) A separate service ingests 200,000 sensor readings per second and mostly reads the last hour of data for one sensor. Would you prefer a B-tree-based or an LSM-based store, and why?
(a) Indexes:
-
(b) Engine:(a) Indexes:
- UNIQUE index on email: exact lookups and prevents duplicate accounts.
- Composite index on (city, signup_date): the first column filters, the second gives
the sort order, so the query reads rows already in order.
- Index on signup_date: "signed up today" becomes a small range scan.
(The (city, signup_date) index can't serve this alone because city comes first.)
Don't index everything: each index slows every insert and update.
(b) LSM-based (e.g. Cassandra, ScyllaDB, a time-series DB built on LSM). The workload
is very write-heavy; LSM turns writes into fast sequential appends. Key the data by
(sensor_id, time bucket) with time as the sort key, so "last hour for one sensor" is
a single sorted range read. Old data can be expired with TTLs or dropped by time bucket.Summary
- An index is a sorted structure that finds rows without scanning the whole table; it speeds up reads and slows down writes.
- Composite indexes work left to right: (a, b) helps queries on a, or on a and b, but not on b alone.
- B-trees keep sorted pages updated in place; a lookup takes a few page reads, which suits read-heavy workloads.
- LSM trees buffer writes in memory, flush sorted files and merge them later; writes are fast and sequential, reads may check several files.
- Write-ahead logs make both engines durable: a change is logged before it is applied.