Indexes and Storage Engines
Learn how B-tree and LSM-tree indexes work, what composite and covering indexes do, and how indexes trade write cost for read speed.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Relational Databases and SQL for Design
Without an index, a database scans every row. With the right index, it jumps straight to the data. Index choices are some of the highest leverage decisions in a design.
B-trees
The default in PostgreSQL and MySQL. A balanced tree of pages keeps keys sorted, so lookups, range scans and ORDER BY are fast (logarithmic). Each write must update every index on the table, so more indexes mean slower inserts.
LSM trees
Used by Cassandra, RocksDB, ScyllaDB and many NoSQL stores. Writes go to an in-memory table and are flushed as sorted, immutable files that are merged in the background (compaction). Writes are very fast and sequential; reads may check several files, helped by Bloom filters that say "definitely not here".
Index types to know
- Composite index on (user_id, created_at): serves "latest orders for a user". Column order matters; the index helps queries that filter on the leftmost columns.
- Covering index: contains every column the query needs, so the table is never touched.
- Unique index: enforces uniqueness (one account per phone number).
- Hash, GIN, GiST and full-text indexes for special cases (equality only, JSON and arrays, geo data, text search).
- Secondary indexes in distributed databases can be local (per shard) or global, with very different costs.
Reading query plans
Use EXPLAIN ANALYZE to see whether a query uses an index or does a sequential scan. Low-selectivity columns (a boolean is_active) rarely benefit from their own index.
Pitfalls
- Indexing every column "just in case" and tanking write throughput.
- Wrapping an indexed column in a function (WHERE lower(email) = ...) and silently losing the index.
- Wrong column order in composite indexes.
You are ready to move on when you can design the indexes for an orders table given its three most common queries and read an EXPLAIN plan to confirm they are used.
Key concepts
- B-tree indexes
- LSM trees and compaction
- Composite index column order
- Covering indexes
- Bloom filters
- EXPLAIN ANALYZE
- Local vs global secondary indexes
Mini project
Load 5 million fake orders into PostgreSQL. Time three queries with no indexes, then add the right composite and covering indexes, and record the speedup and the change in bulk insert time.
Check yourself
You have an index on (city, created_at). Will it help a query that filters only on created_at? Why or why not?
Free resources
- Use The Index, Luke (Markus Winand)
- PostgreSQL indexes (PostgreSQL)
- Bloom filter (Wikipedia)