Skip to the content

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

SituationExampleFix
A function on the columnWHERE lower(email) = 'a@b.com' with an index on emailAn expression index: CREATE INDEX ON users (lower(email))
Leading wildcardWHERE name LIKE '%son'Full-text search or a trigram index (pg_trgm)
Not the leftmost columnIndex (a, b), query on b onlyAnother index, or reorder
Low selectivityWHERE type = 'purchase' matches a third of the tableCorrect behaviour: a sequential scan is faster when you need a large share of rows
Type mismatchComparing a text column to a numberUse matching types
Outdated statisticsThe planner thinks the table is tinyANALYZE (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_indexes shows 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)

TypeFor
B-treeThe default: equality, ranges, sorting
HashEquality only (B-tree is usually just as good)
GINjsonb contents, arrays, full-text search, trigram similarity
GiST / SP-GiSTGeometry, ranges, nearest-neighbour searches
BRINHuge tables where values follow physical order (time-series logs); tiny size
Partial indexIndex only some rows: CREATE INDEX ON orders (created_at) WHERE status = 'pending'
Unique indexEnforces 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

WordMeaning
IndexA sorted structure that speeds up lookups
Sequential scanReading every row of a table
B-treeThe default balanced, sorted tree index
Composite indexAn index on several columns
Leftmost-prefix ruleA composite index serves queries on its first columns
Covering indexContains every column a query needs
Index-only scanAnswering from the index without reading the table
SelectivityHow small a share of rows a condition matches
Expression indexAn index on a calculated value like lower(email)
Partial indexAn index on only some rows

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.