Indexing
An index is an extra data structure that lets a database find rows without reading the whole table, the same way a book’s index lets you jump to a page instead of reading every page. It is a sorted, compact copy of one or more columns with pointers back to the rows. Indexes make reads dramatically faster and make every write a little slower, because each insert or update must also update the index.
From full scan to index lookup
- The orders table is stored as pages on disk, rows in the order they were inserted. We want one row: id = 642.
- With no index, the database must read every page and check every row: a sequential scan. Cost grows with the table.
- A B-tree index on
idkeeps keys sorted in a shallow tree. Each node holds many keys and points to the right child for each range. - Lookup: root says 642 is between 400 and 800, the next node sends it right of 600, the leaf holds 642 → page 12. Four page reads instead of sixteen. On a billion rows, the tree is still only 3 to 5 levels deep.
- Leaves are linked in key order, so range queries and
ORDER BY iddescend once and then walk sideways.
Index types
| Type | Structure | Good for | Found in |
|---|---|---|---|
| B-tree | Balanced sorted tree | Equality, ranges, sorting; the default | PostgreSQL, MySQL, SQL Server, Oracle, SQLite |
| Hash | Hash table | Equality only | PostgreSQL hash, in-memory stores |
| LSM-tree | Sorted in-memory buffer flushed to sorted files, merged in the background | Very high write rates | Cassandra, RocksDB, ScyllaDB, ClickHouse MergeTree (similar idea) |
| Inverted (GIN) | Term → list of rows | Full-text search, JSON, arrays | Elasticsearch, OpenSearch, PostgreSQL GIN |
| BRIN / zone maps | Min/max per block of rows | Huge, naturally ordered tables (time series) | PostgreSQL BRIN, Parquet statistics, Snowflake micro-partitions |
| Bitmap | One bit-array per distinct value | Low-cardinality columns in analytics | Oracle, Druid, Pinot |
| Vector (HNSW, IVF) | Graph or clusters of embeddings | Nearest-neighbour search | pgvector, Milvus, Elasticsearch |
Analytical warehouses rarely use B-trees. They rely on columnar storage, partitioning and min/max statistics to skip data instead, as explained on the Parquet page.
Designing good indexes
- Index what you filter and join on. Start from real slow queries and their
EXPLAINplans, not from guesses. - Selectivity matters. An index on
statuswith three values rarely helps; the database will scan anyway. - Composite indexes follow the leftmost-prefix rule. An index on
(customer_id, created_at)servesWHERE customer_id = 7andWHERE customer_id = 7 AND created_at > ..., but notWHERE created_at > ...alone. - Covering indexes (
INCLUDE (amount)in PostgreSQL) answer a query from the index alone, skipping the heap. - Every index costs disk space, memory and write time. A table with ten indexes does eleven writes per insert.
Indexes in sharded systems
When data is sharded by one key, an index on a different column has two possible shapes:
| Local (document-partitioned) index | Global (term-partitioned) index | |
|---|---|---|
| Where it lives | Each shard indexes only its own rows | The index itself is sharded by the indexed value |
| Writes | Cheap: one shard | Touch the data shard and an index shard, often asynchronously |
| Reads by indexed column | Ask every shard (scatter-gather) | Ask one index shard |
| Examples | Elasticsearch, MongoDB, Cassandra secondary indexes | DynamoDB global secondary indexes, Spanner, CockroachDB |
DynamoDB global secondary indexes are updated asynchronously, so they are eventually consistent: a read right after a write can miss it. See Consistency vs Eventual Consistency.
Common mistakes
- Wrapping the column in a function.
WHERE LOWER(email) = ...cannot use a plain index onemail; create an expression index or store the normalized value. - Leading wildcards.
LIKE '%gmail.com'cannot use a B-tree; use a trigram (pg_trgm) or full-text index. - Indexing everything “just in case”. Unused indexes slow every write. Check
pg_stat_user_indexesand drop the dead ones. - Forgetting bulk loads. For a big backfill, drop or disable secondary indexes, load, then rebuild.
- Implicit type casts. Comparing a
varcharcolumn to a number can disable the index.
Learning Resources
Books and sites
- Use The Index, Luke: Markus Winand’s free guide to SQL indexing
- Database Internals, Alex Petrov: B-trees and LSM-trees in depth
- Designing Data-Intensive Applications (2nd ed.), Martin Kleppmann and Chris Riccomini: storage and retrieval, and the partitioning chapter on secondary indexes