A database index is an extra data structure, kept in sync with a table, that lets the database find rows without reading the whole table. It turns a scan of 100 million rows into three or four page reads. Indexes are the most important performance tool in any database, but they aren't free: every index costs storage, memory and write throughput, and an index the query can't use is pure overhead.
Think of it like
The index at the back of a book
To find every mention of "replication" you don't read all 600 pages; you flip to the index, which is sorted alphabetically and points to page numbers. A phone book sorted by (last name, first name) works the same way: finding "Smith, Ana" is instant, but finding everyone whose first name is Ana means reading the whole book. That is the leftmost-prefix rule in one sentence.
Why indexes matter
Without an index, SELECT * FROM users WHERE email = 'ana@example.com' forces a full table scan: the database reads every page and checks every row. With a B+ tree index on email, it descends a short, wide tree and lands on the one matching entry.
Table size
100 M rows
say 50 GB on disk
Full scan
seconds
reads every page
B+ tree height
3–4 levels
fan-out ≈ 500 keys per page
Indexed lookup
~4 page reads
often < 1 ms when cached
The simulation above compares a full scan with an index lookup step by step. The rest of this lesson covers how indexes are built, which queries can use them, and what they cost.
B+ tree indexes
The default index in PostgreSQL, MySQL (InnoDB), SQL Server, Oracle and SQLite is the B+ tree, a balanced tree whose nodes are disk pages (8 KB in Postgres, 16 KB in InnoDB). Internal pages hold separator keys and child pointers; leaf pages hold the keys plus a pointer to the row (or the row itself) and are linked to their neighbors, which makes range scans a simple walk along the leaves. See B-Trees & B+ Trees for the data structure in depth.
- 1
Start at the root
For
WHERE id = 4217, read the root page and binary-search its keys to pick a child. - 2
Descend
Repeat on each internal page. Every level narrows the range by a factor of a few hundred.
- 3
Reach the leaf
The leaf holds key
4217and a pointer to its row (a heap tuple ID in Postgres, the primary key in InnoDB secondary indexes). - 4
Fetch the row
Read the row's page, unless the index alone answers the query (a covering index).
- 5
Range scans
For
BETWEEN 4217 AND 4300, find the first key, then follow the leaf-to-leaf links in sorted order.
Hash indexes
B+ tree
- Equality, ranges, prefixes and
ORDER BYon indexed columns - O(log n) lookups: a few page reads
- The right default for almost everything
Hash index
- Equality lookups only:
=andIN - O(1) on average; no ordering, ranges or prefix matching
- Postgres
USING HASH, MySQL MEMORY tables, InnoDB's automatic adaptive hash index, Bitcask-style key-value stores
Clustered vs non-clustered indexes
Clustered
- The table's rows are stored inside the index, in key order
- Only one per table (rows can be sorted only one way)
- InnoDB always clusters by primary key; SQL Server lets you choose
- Primary-key range scans are sequential and very fast
Non-clustered (secondary)
- A separate structure whose leaves point at rows
- Many per table
- InnoDB secondary leaves store the primary key, so a lookup is two tree descents
- Postgres stores rows in an unordered heap; every index is secondary and points to a tuple ID
Composite indexes and the leftmost-prefix rule
A composite index on (a, b, c) is sorted by a, then by b within equal a, then by c. The database can only seek using a leftmost prefix of those columns, exactly like a phone book sorted by last name, then first name.
CREATE INDEX idx_orders_user_status_date
ON orders (user_id, status, created_at);| Query predicate | Can it seek? | Why |
|---|---|---|
WHERE user_id = 42 | Yes | Leftmost column |
WHERE user_id = 42 AND status = 'paid' | Yes | Prefix (user_id, status) |
WHERE user_id = 42 AND status = 'paid' AND created_at > '2026-01-01' | Yes, fully | Equalities first, then a range on the last column |
WHERE user_id = 42 ORDER BY status, created_at | Yes, no sort needed | Rows come out of the index already ordered |
WHERE user_id = 42 AND created_at > '2026-01-01' | Partly | Seeks on user_id; created_at is only filtered, because status sits between them |
WHERE user_id > 40 AND status = 'paid' | Partly | A range on the first column stops seeking on later columns |
WHERE status = 'paid' | Usually no | Skips the leftmost column (some engines can "skip scan" when user_id has few distinct values) |
Covering indexes
If an index contains every column a query needs, the database never touches the table: Postgres shows an Index Only Scan, MySQL shows Using index. Extra non-key columns can ride along in the leaf pages with INCLUDE (PostgreSQL 11+, SQL Server).
-- The user's 20 most recent paid orders, with totals
SELECT created_at, total_cents
FROM orders
WHERE user_id = 42 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;
-- Seek on (user_id, status), read created_at already sorted, carry total_cents along
CREATE INDEX idx_orders_recent_paid
ON orders (user_id, status, created_at DESC)
INCLUDE (total_cents);Selectivity: when the planner ignores your index
Selectivity is how small a fraction of rows a predicate matches. An index on country is useless for WHERE country = 'US' if 60% of users are American: thousands of random page reads through the index cost more than one sequential scan. The planner estimates this from table statistics (refreshed by ANALYZE) and chooses accordingly; indexes typically pay off when a query returns a small percentage of the table.
- A function wraps the column:
WHERE LOWER(email) = ...can't use an index onemail; create an expression index instead. - Implicit casts: comparing a
VARCHARcolumn to a number can force a per-row conversion and a scan (MySQL). - Leading wildcards:
LIKE '%son'cannot seek a B+ tree;LIKE 'son%'can. Use trigram or full-text indexes for substrings. - Low selectivity or tiny tables: a sequential scan is genuinely cheaper.
- Stale statistics: the planner misjudges row counts; run
ANALYZE.
-- Expression index: makes case-insensitive lookups indexable
CREATE INDEX idx_users_email_lower ON users (LOWER(email));
SELECT id FROM users WHERE LOWER(email) = 'ana@example.com';
-- Partial index: index only the rows you actually query (small and selective)
CREATE INDEX idx_orders_pending ON orders (created_at) WHERE status = 'pending';Reading EXPLAIN
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id, total_cents FROM orders WHERE user_id = 42 AND status = 'paid';
-- Before: scan 100 M rows in parallel to find 51
-- Gather (actual time=2.1..3874.5 rows=51 loops=1)
-- Workers Planned: 2
-- -> Parallel Seq Scan on orders (actual time=1270.2..3861.7 rows=17 loops=3)
-- Filter: ((user_id = 42) AND ((status)::text = 'paid'::text))
-- Rows Removed by Filter: 33333316
-- Execution Time: 3874.6 ms
-- After CREATE INDEX ... ON orders (user_id, status, created_at):
-- Index Scan using idx_orders_user_status_date on orders (actual time=0.028..0.112 rows=51 loops=1)
-- Index Cond: ((user_id = 42) AND ((status)::text = 'paid'::text))
-- Execution Time: 0.139 ms| Plan node | Meaning | Verdict |
|---|---|---|
| Seq Scan | Read the whole table | Fine for small tables or large fractions; a red flag for selective queries on big tables |
| Index Scan | Descend the index, then fetch each matching row | Good for selective predicates |
| Index Only Scan | Answer entirely from the index | Best case |
| Bitmap Index Scan + Bitmap Heap Scan | Collect matching row locations, then read their pages in physical order | Medium selectivity, or combining several indexes |
Sort (MySQL: Using filesort) | An explicit sort step | Consider an index that matches the ORDER BY |
| Nested Loop / Hash Join / Merge Join | Join strategies | Check estimated vs actual row counts |
The cost of indexes: write amplification
Every INSERT must add an entry to every index on the table, every DELETE must remove them, and every UPDATE touching an indexed column must move entries. A table with eight indexes turns one logical row write into nine structure updates, each potentially a random page write plus WAL. Indexes also compete with table data for buffer-pool memory.
- Index for your most frequent and most important queries, not for every column.
- Drop redundant indexes:
(a)is redundant when(a, b)exists. - Find unused indexes and remove them (query below).
- Build indexes without blocking writes:
CREATE INDEX CONCURRENTLYin Postgres, online DDL (ALGORITHM=INPLACE, LOCK=NONE) in MySQL.
SELECT relname AS table_name,
indexrelname AS index_name,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;LSM trees: built for writes
B+ trees update pages in place, which means random I/O on every write. Log-structured merge trees (LSM trees) instead buffer writes in memory and write them to disk sequentially in large sorted batches. They power RocksDB, LevelDB, Cassandra, ScyllaDB, HBase and Bigtable.
- 1
Append to the WAL
Every write is first appended to a commit log for durability. Sequential appends are fast on any disk.
- 2
Insert into the memtable
The write goes into an in-memory sorted structure, often a Skip Lists implementation. It is acknowledged now, with no random disk I/O.
- 3
Flush to an SSTable
When the memtable fills (tens of MB), it is written out as an immutable, sorted SSTable file, with a sparse index and a Bloom filter.
- 4
Read newest to oldest
Reads check the memtable, then SSTables from newest to oldest; the first version found wins. Per-file Bloom filters skip files that definitely don't hold the key.
- 5
Compact in the background
Compaction merge-sorts SSTables into larger ones, discarding overwritten values and deletion markers (tombstones).
| Dimension | B+ tree | LSM tree |
|---|---|---|
| Write pattern | Update pages in place (random I/O) | Append and flush sorted files (sequential I/O) |
| Write throughput | Moderate | High |
| Point reads | Predictable: one tree descent | May check several levels; Bloom filters and block caches keep it fast |
| Range scans | Excellent: walk the linked leaves | Good, but must merge results from several levels |
| Write amplification | Rewrites a whole 8–16 KB page for a small change, plus WAL | Compaction rewrites data as it moves down levels, often 10× or more |
| Space usage | Partially empty pages after splits | Obsolete versions linger until compaction; compresses well |
| Background work | Page splits; VACUUM in Postgres | Compaction, which can cause latency spikes if it falls behind |
| Used by | PostgreSQL, MySQL InnoDB, SQL Server, Oracle, SQLite | RocksDB, LevelDB, Cassandra, ScyllaDB, HBase, Bigtable |
Secondary indexes in distributed databases
When a table is partitioned by primary key across many nodes (see Sharding & Partitioning), an index on another attribute, such as color, has to be partitioned too. There are two ways to do it, and they trade read cost against write cost.
Local (document-partitioned)
- Each partition indexes only its own rows
- Writes update one partition: simple and consistent
- Reads by the indexed attribute must scatter to every partition and gather results; tail latency grows with partition count
- Examples: MongoDB, Cassandra secondary indexes, Elasticsearch shards, DynamoDB local secondary indexes
Global (term-partitioned)
- The index is partitioned by the indexed value itself (all
redentries live together) - Reads go to one index partition, then fetch matching rows
- One row write may update index partitions on other nodes, so updates are usually asynchronous or need distributed transactions
- Examples: DynamoDB global secondary indexes (eventually consistent), Spanner and CockroachDB (transactional)
Complexity
| Structure | Point lookup | Range scan (k results) | Insert | Notes |
|---|---|---|---|---|
| No index (full scan) | O(n) | O(n) | O(1) | Reads every page |
| B+ tree | O(log n) | O(log n + k) | O(log n) | Default in relational databases; 3–4 page reads |
| Hash index | O(1) | Not supported | O(1) | Equality only; no ordering |
| LSM tree | O(log n) per level checked | O(log n + k) merged across levels | O(log m) in memory | m = memtable size; flushes and compaction are sequential I/O |
n = rows, k = rows returned. In practice, the number of disk pages touched matters far more than comparisons.
Key takeaways
- An index trades extra storage and slower writes for dramatically faster reads: O(log n) page reads instead of a full scan.
- B+ trees support equality, ranges and ordering; hash indexes support equality only.
- Composite indexes follow the leftmost-prefix rule: put equality columns first, sort columns next, range columns last.
- Covering indexes answer queries from the index alone; use
EXPLAIN ANALYZEto confirm what the planner actually does. - LSM trees turn random writes into sequential ones (memtable, SSTables, compaction, Bloom filters) at the cost of read and compaction overhead.
- In distributed databases, local secondary indexes make reads scatter-gather; global ones make writes cross-partition.
Common pitfalls
- Indexing every column "just in case", slowing every write and bloating memory.
- Defining
(status, user_id)when queries filter byuser_idalone, so the index can't seek. - Wrapping indexed columns in functions or casts (
LOWER(email), implicit type conversion) and silently losing the index. - Expecting an index on a low-selectivity column (booleans, country) to speed up queries that match a large fraction of rows.
- Creating indexes on large production tables with a blocking
CREATE INDEXinstead of a concurrent or online build.
Interview tips
- Tie every index to a specific query and explain its column order.
- Know the B-tree vs LSM trade-off and which databases use which; it often decides storage-engine questions.
- Mention write amplification when proposing many indexes on a write-heavy table.
Real-world applications
- Primary-key and unique constraints (always backed by an index).
- Timeline and feed queries via composite indexes on
(owner_id, created_at). - Case-insensitive login lookups via expression indexes.
- Write-heavy event and metrics storage on LSM engines (Cassandra, RocksDB).
- Secondary lookups in DynamoDB via global secondary indexes.
Test yourself
Given an index on (last_name, first_name), which query cannot use it to seek?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.