$ EXPLAIN SELECT * FROM orders WHERE id = 642;

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

$ SELECT * FROM orders WHERE id = 642
Full table scan vs B-tree index lookup
orders: 16 pages on disk HEAP · table pages, rows in insert order SEQ SCAN · 16 / 16 pages read ROOT · 400 | 800 < 200 | ≥ 200< 600 | ≥ 600< 1000 | ≥ 1000 1–199200–399400–599 600–799800–9991000+ INDEX SCAN · 3 index + 1 heap page id 642 → page 12 leaves are linked: id BETWEEN 600 AND 999 = 1 descent + walk right
  1. The orders table is stored as pages on disk, rows in the order they were inserted. We want one row: id = 642.
  2. With no index, the database must read every page and check every row: a sequential scan. Cost grows with the table.
  3. A B-tree index on id keeps keys sorted in a shallow tree. Each node holds many keys and points to the right child for each range.
  4. 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.
  5. Leaves are linked in key order, so range queries and ORDER BY id descend 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 EXPLAIN plans, not from guesses.
  • Selectivity matters. An index on status with three values rarely helps; the database will scan anyway.
  • Composite indexes follow the leftmost-prefix rule. An index on (customer_id, created_at) serves WHERE customer_id = 7 and WHERE customer_id = 7 AND created_at > ..., but not WHERE 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 on email; 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_indexes and drop the dead ones.
  • Forgetting bulk loads. For a big backfill, drop or disable secondary indexes, load, then rebuild.
  • Implicit type casts. Comparing a varchar column 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

Docs

Videos