A slow search can cost a project hours of user frustration.
B‑tree indexes turn those scans into instant lookups, but only if you understand how they work and how to use them effectively.
TL;DR
- B‑trees keep data sorted in disk‑aligned pages, giving O(log n) lookups.
- Point queries touch a single root‑to‑leaf path; range queries walk contiguous leaf nodes.
- Composite and covering indexes eliminate extra row fetches.
- Over‑indexing hurts writes; use partial or filtered indexes when appropriate.
The Anatomy of a B‑Tree Index
A B‑tree is a balanced, multi‑way search tree optimized for disk storage.
- Leaf nodes store the actual key‑value pairs. Each leaf holds a block of keys and a pointer to the corresponding row (or a tuple ID).
- Internal nodes hold a subset of keys that partition the key space and pointers to child nodes. They act like a decision tree: at each level you choose the child that contains the target key.
- Balanced height is maintained by splitting and merging nodes when inserts or deletes change the number of keys. Because the tree is balanced, the depth is logarithmic in the number of indexed rows.
Disk‑based B‑trees group nodes to match the underlying block size (e.g., 8 KB). This minimizes the number of I/O operations: one read brings an entire node into memory, and the buffer pool can cache it for future queries.
How B‑Trees Reduce I/O for Point Queries
A point query (e.g., WHERE id = 42) follows a single path from the root to the leaf that contains the target key. Each step requires reading one page; with a balanced tree the number of pages read is ceil(log_f(n)), where f is the fan‑out (number of pointers per node).
Because the pages are cached in the buffer pool, repeated lookups for the same or nearby keys hit RAM instead of disk. In PostgreSQL, the planner can also perform an Index Only Scan: if the query requests only columns that are part of the index, PostgreSQL can return the result directly from the index pages, skipping the main table entirely.
This reduces I/O from O(n) for a full table scan to O(log n) for the index path, and often to O(1) if the required pages are already in memory.
Range Queries and the Power of In‑order Traversal
Range conditions (BETWEEN, >=, <=) map naturally to a contiguous segment of leaf nodes. Once the index reaches the first qualifying leaf, it can walk the leaf pages sequentially, following the linked list that connects them.
Because the leaves are stored in sorted order, the engine can fetch all matching rows with a single sequential read of the relevant pages. This is why a range query on a well‑indexed column can be as fast as a full scan when the range covers a large portion of the table, yet still orders of magnitude faster when the range is selective.
Indexing Strategies: Single vs Composite vs Covering
| Strategy | When to use | Pros | Cons |
|---|---|---|---|
| Single‑column | Simple predicates on one column | Easy to maintain; minimal storage | May require a second lookup to fetch non‑indexed columns |
| Composite | Multiple columns in the WHERE clause or ORDER BY | Eliminates extra lookups; preserves column order | Larger index; can’t be used if only a subset of columns matches |
| Covering | Query needs only a few columns | Planner can use index only; no heap fetch | Must include all requested columns; larger index |
Composite indexes are especially useful when a query filters on several columns or orders by them. PostgreSQL can use the leftmost prefix of a composite index, so an index on (last_name, first_name, created_at) can also serve a query that only filters on last_name.
Covering indexes—indexes that include all columns required by a query—allow the planner to perform an Index Only Scan. They are a powerful tool for read‑heavy workloads but increase index size.
Real‑World Example: Optimizing a Search Feature
Suppose we have a users table that powers a search bar:
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
last_name VARCHAR(255) NOT NULL,
first_name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);
1. Create a Composite B‑Tree Index
We want to support searches by name prefix and recent activity:
CREATE INDEX users_last_first_created_idx
ON users (last_name, first_name, created_at DESC);
The descending order on created_at ensures that recent users appear first when we sort by date.
2. Point Query Example
EXPLAIN ANALYZE
SELECT id, last_name, first_name
FROM users
WHERE id = 123456;
Plan (before index):
Seq Scan on users (cost=0.00..12.34 rows=1 width=64)
Filter: (id = 123456)
Plan (after index on id):
Index Scan using users_pkey on users (cost=0.42..2.44 rows=1 width=64)
Index Cond: (id = 123456)
The index scan reads only the page containing the target row, whereas the sequential scan reads the entire table.
3. Range Query Example
EXPLAIN ANALYZE
SELECT id, last_name, first_name, created_at
FROM users
WHERE last_name = 'Smith'
AND created_at >= now() - interval '30 days'
ORDER BY created_at DESC
LIMIT 10;
Plan (before composite index):
Seq Scan on users (cost=0.00..2000.00 rows=1000 width=128)
Filter: ((last_name = 'Smith') AND (created_at >= now() - interval '30 days'))
Rows Removed by Filter: 999000
Plan (after composite index):
Index Only Scan using users_last_first_created_idx on users (cost=0.42..12.34 rows=10 width=128)
Index Cond: ((last_name = 'Smith') AND (created_at >= now() - interval '30 days'))
Heap Fetches: 10
The index scan jumps directly to the first leaf that satisfies last_name = 'Smith' and then walks the leaf nodes for the next 30 days of activity. Only 10 rows are fetched from the heap, and the planner can use the index pages alone because all requested columns are present.
4. Comparing I/O
- Without index: 1 M rows scanned → ~200 MB read.
- With composite index: ~10 KB of index pages read + 10 KB of heap fetches.
The difference is dramatic; the query completes in milliseconds instead of seconds.
Common Pitfalls and Trade‑offs
| Pitfall | Why it Happens | Mitigation |
|---|---|---|
| Over‑indexing | Each write touches every relevant index. | Keep indexes to the minimum needed for read workloads; drop unused indexes. |
| Large indexes | They consume buffer pool space, causing evictions. | Use partial indexes for predicates that match a small fraction of rows; consider pg_repack or pg_dump/restore to shrink. |
| Data type bloat | TEXT columns can store arbitrary length, making keys large. |
Use VARCHAR(n) or CHAR(n) for fixed‑length keys; normalize to separate tables if necessary. |
| Missing covering columns | Query needs columns not in the index, forcing a heap fetch. | Add the columns to the index as INCLUDE (PostgreSQL 11+) or as part of the composite key. |
| Ignoring statistics | Planner may misestimate cost and choose the wrong index. | Run ANALYZE regularly; tune default_statistics_target for highly selective columns. |
| Index fragmentation | Frequent updates cause node splits and dead tuples. | Run VACUUM/VACUUM FULL or pg_repack to defragment. |
Key takeaways
- B‑trees keep data sorted in disk‑aligned pages, enabling O(log n) point lookups.
- Point queries follow a single root‑to‑leaf path; range queries walk contiguous leaf nodes.
- Composite indexes can cover multi‑column predicates and, when all needed columns are present, enable index‑only scans.
- Proper index design balances read performance against write overhead and storage cost.
- Regular maintenance (ANALYZE, VACUUM) and careful data‑type selection keep indexes efficient.