Lesson 220 of 296
Indexes: B-tree, composite and covering
What you will learn
- What an index is and how a B-tree works
- Creating indexes and seeing them used
- Composite indexes and the leftmost-prefix rule
- Covering indexes and index-only scans
- When indexes are not used
- The costs of indexes, and other index types
On this page
Why indexes?
Without an index, finding user_id = 42 in a table of 200,000 rows means reading every row: a sequential scan (full table scan), O(n).
An index is a separate, sorted data structure that points to rows, like the index at the back of a book: you look up the word, then go straight to the page. With an index the lookup is about O(log n).
B-tree indexes
The default index type is the B-tree (balanced tree, Lesson 133 covered trees): a short, wide tree of sorted keys. Even with millions of rows it is only 3 or 4 levels deep, so finding a value takes a handful of page reads. Because keys are sorted, a B-tree supports =, <, >, BETWEEN, ORDER BY and prefix LIKE 'abc%'.
PostgreSQL automatically creates an index for every primary key and unique constraint. Foreign key columns are not indexed automatically: index them yourself (joins and deletes need them).
Seeing it work
These results come from a real PostgreSQL test table with 200,000 rows:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id integer NOT NULL,
type text NOT NULL,
created_at timestamptz NOT NULL
);Before any index:
EXPLAIN SELECT * FROM events WHERE user_id = 42;
Seq Scan on events (cost=0.00..3971.00 rows=40 width=26)
Filter: (user_id = 42)Create an index and ask again:
CREATE INDEX events_user_id_idx ON events (user_id);
Bitmap Heap Scan on events (cost=4.60..145.32 rows=40 width=26)
Recheck Cond: (user_id = 42)
-> Bitmap Index Scan on events_user_id_idx (cost=0.00..4.59 rows=40 width=0)
Index Cond: (user_id = 42)The estimated cost fell from about 3,971 to 145. (EXPLAIN is explained in Lesson 221.)
Composite (multi-column) indexes
A common query: "the latest 10 events for user 42":
SELECT * FROM events WHERE user_id = 42 ORDER BY created_at DESC LIMIT 10;With only the user_id index, PostgreSQL finds the user's rows and then sorts them (Sort step). A composite index on both columns, in the right order, removes the sort:
CREATE INDEX events_user_created_idx ON events (user_id, created_at DESC);
Limit (cost=0.42..41.58 rows=10 width=26)
-> Index Scan using events_user_created_idx on events (cost=0.42..165.07 rows=40 width=26)
Index Cond: (user_id = 42)The index is sorted by user_id, and within each user by created_at, so the database reads the first 10 entries and stops.
The leftmost-prefix rule: an index on (a, b, c) helps queries that filter on a, on a and b, or on a, b and c. It does not help a query filtering only on b or only on c, just as a phone book sorted by surname then first name does not help you find everyone called "Sam".
Column order: put columns used with equality (=) first, then the column used for ranges or sorting. (user_id, created_at) serves "user 42, newest first" and "user 42 since March"; (created_at, user_id) serves neither well.
Covering indexes and index-only scans
If all the columns a query needs are in the index, the database can answer from the index without visiting the table at all:
EXPLAIN SELECT user_id, created_at FROM events WHERE user_id = 42 ORDER BY created_at DESC LIMIT 10;
Limit (cost=0.42..41.58 rows=10 width=12)
-> Index Only Scan using events_user_created_idx on events (...)
Index Cond: (user_id = 42)Index Only Scan: fastest. Extra columns can be stored in an index without being part of the sort key: CREATE INDEX ... ON orders (customer_id) INCLUDE (status, total_pence). This is a covering index.
When an index is not used
| Situation | Example | Fix |
|---|---|---|
| A function on the column | WHERE lower(email) = 'a@b.com' with an index on email | An expression index: CREATE INDEX ON users (lower(email)) |
| Leading wildcard | WHERE name LIKE '%son' | Full-text search or a trigram index (pg_trgm) |
| Not the leftmost column | Index (a, b), query on b only | Another index, or reorder |
| Low selectivity | WHERE type = 'purchase' matches a third of the table | Correct behaviour: a sequential scan is faster when you need a large share of rows |
| Type mismatch | Comparing a text column to a number | Use matching types |
| Outdated statistics | The planner thinks the table is tiny | ANALYZE (autovacuum normally handles this) |
In the test table, WHERE lower(type) = 'click' AND user_id = 7 used the user_id index and then applied lower(type) = 'click' as a filter on the matching rows: the function prevented any index on type from being used. And WHERE type = 'purchase' AND created_at > '2026-04-01' (about 23,000 matching rows) used a sequential scan, because reading that many rows through an index would be slower.
Costs of indexes
Indexes are not free:
- Every INSERT, UPDATE and DELETE must update every index on the table: writes get slower.
- They use disk and memory.
- Unused indexes are pure cost. PostgreSQL's
pg_stat_user_indexesshows how often each index is used.
Index for your real queries: columns in WHERE, JOIN and ORDER BY of frequent or slow queries, plus foreign keys. Do not index every column "just in case".
Other index types (PostgreSQL)
| Type | For |
|---|---|
| B-tree | The default: equality, ranges, sorting |
| Hash | Equality only (B-tree is usually just as good) |
| GIN | jsonb contents, arrays, full-text search, trigram similarity |
| GiST / SP-GiST | Geometry, ranges, nearest-neighbour searches |
| BRIN | Huge tables where values follow physical order (time-series logs); tiny size |
| Partial index | Index only some rows: CREATE INDEX ON orders (created_at) WHERE status = 'pending' |
| Unique index | Enforces uniqueness (what UNIQUE constraints use) |
| Vector (pgvector: HNSW, IVFFlat) | Similarity search on embeddings for AI features (Lesson 276) |
Creating an index on a big, busy production table locks writes; use CREATE INDEX CONCURRENTLY (slower, but no long lock) in migrations (Lesson 228).
How to say it in an interview
"An index is a separate sorted structure, usually a B-tree, that lets the database find rows in logarithmic time instead of scanning the whole table, and supports equality, ranges and ordering. Primary keys and unique constraints are indexed automatically but foreign keys are not. For composite indexes the leftmost-prefix rule applies, so I put equality columns first and the range or sort column last, which can remove the sort step entirely; if every needed column is in the index, I get an index-only scan. Indexes are skipped when the column is wrapped in a function, for leading wildcards, or when many rows match, and every index slows writes, so I index for real query patterns and verify with EXPLAIN."
Key words
| Word | Meaning |
|---|---|
| Index | A sorted structure that speeds up lookups |
| Sequential scan | Reading every row of a table |
| B-tree | The default balanced, sorted tree index |
| Composite index | An index on several columns |
| Leftmost-prefix rule | A composite index serves queries on its first columns |
| Covering index | Contains every column a query needs |
| Index-only scan | Answering from the index without reading the table |
| Selectivity | How small a share of rows a condition matches |
| Expression index | An index on a calculated value like lower(email) |
| Partial index | An index on only some rows |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.