What you'll learn: By the end of this lesson you will be able to explain how a PostgreSQL B-tree finds a row in a few page reads, say which conditions it can serve, choose the column order of a composite index from the queries it must answer, spot a query that hides its column behind a function, decide when covering and partial indexes pay off, and count what each extra index costs on writes and disk. A lab on real PostgreSQL code measures each effect in pages touched.
Think of the index at the back of a textbook. To find "photosynthesis" you look the word up in a sorted list, get a page number and turn to it. The list only helps for the words it holds, in the order it is sorted, and whoever adds a chapter must also update it, so every extra index is extra work at writing time.
A database index is that sorted list. This lesson is the dedicated treatment of the most common kind, the B-tree: how it is built, which questions it answers, its variations (single-column, composite, covering, partial and expression) and what each costs. It builds on Databases: the basics, which introduces indexes in a paragraph, and Storage engines, which compares B-trees with LSM-trees. SQL joins and reading plans with EXPLAIN ANALYZE are separate lessons in this module.
Verified with the PostgreSQL 18 documentation and the lab below on PGlite 0.6.1 (real PostgreSQL compiled to WebAssembly, which reports PostgreSQL 19.0), on 2026-12-01.
The core idea
A B-tree index keeps a sorted copy of one or more columns, with a pointer to the table row for each entry, in a balanced tree of pages. Finding a value walks a few levels down the tree; the same sorted order serves ranges and ORDER BY. The planner uses the index only when it expects that to be cheaper than reading the table, so what matters is the match between the index, the query and the data.
Three illustrations run through the lesson, each labelled:
- Minimal example: a 20,000-row
orderstable and an index onshopper_id. - Realistic example: ShopStream's order history and "pending orders" queue, in "In practice".
- Failure example: an index that exists and is never used, because of a function around the column.
How a B-tree finds a row
PostgreSQL's B-tree is the standard multi-way balanced tree. Any data type that can be sorted into a well-defined order can be indexed this way. The index is made of pages. One metapage sits at a fixed place at the start of the index; all other pages are leaf pages (the lowest level, holding tuples that point to table rows) or internal pages (holding tuples that point to the next level down). Each level is a doubly linked list of pages, and the documentation notes that typically over 99% of all pages are leaf pages.
Figure 1. The path of one lookup. How to read this: the lookup enters at the root. Internal pages route by key range down to one leaf page, and the leaf entry points at the row in the table. The "stack" on the leaf stands for many leaf pages side by side.
When a leaf page cannot fit a new tuple the page is split and a downlink is added to the parent, which can split in turn; when the root cannot fit a new downlink, a root split adds a level on top. That is how the tree stays balanced and grows only as fast as needed. Two documented limits matter in practice: an index entry cannot exceed about one third of a page, and a B-tree leaf page is filled to a fillfactor of 90 by default during a build, leaving room for later inserts.
The lab looks at its own primary key index with the pageinspect extension:
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
9. The shape of a B-tree (pageinspect, on the primary key index)
orders_pkey: 57 pages, level 1 (0 would mean a single leaf page); the root page holds 55 entries, one per leaf page.
For 20,000 integer keys the primary key index is 57 pages: the metapage, one root page, and 55 leaf pages (the root holds 55 entries, one per leaf). Its level is 1: a root page directly above the leaves, so a lookup reads the root and one leaf before it follows the pointer to the table. The tree is shallow because each page holds many entries: height grows with the logarithm of the row count, not with the row count.
What a B-tree can serve
The planner considers a B-tree whenever an indexed column is compared with <, <=, =, >= or >. Combinations such as BETWEEN and IN can be implemented as index searches, and so can IS NULL and IS NOT NULL. A pattern match with LIKE or ~ can use it when the pattern is a constant anchored at the start of the string ('foo%', not '%bar'), and outside the C locale it needs a special operator class. And because the entries are sorted, a B-tree can return rows in order, which can satisfy an ORDER BY without a separate sort step. Only B-tree can produce sorted output among PostgreSQL's built-in index types.
How the planner reaches the rows
Figure 2. The scan types in the lab's plans. How to read this: each diamond is a question the planner answers from statistics. The lab's plans use four of these five outcomes, and the last diamond is the one you influence most by writing the query and the index to match.
A bitmap scan builds a bitmap of matching row locations, then visits the table in physical order. That loses index order, so an ORDER BY needs a separate sort, and it is how the planner can combine several indexes with AND and OR.
An index is not always used
Statistics decide: ANALYZE gathers them, and the planner uses an index when it thinks that is cheaper than a sequential scan. The partial-index page gives the rule of thumb: a query for a common value (more than a few percent of the rows) will not use the index anyway.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
Engine: PostgreSQL 19.0 (PGlite 0.6.1). Table orders: 20000 illustrative rows, 148 pages of 8 kB.
"pages touched" is shared-buffer hits plus reads reported by EXPLAIN (ANALYZE, BUFFERS) for the whole plan.
1. No index: the only way to find shopper 42 is to read every page
A
select * from orders where shopper_id = 42
plan: Seq Scan on orders
rows returned: 10 pages touched: 148
2. create index orders_shopper_idx on orders (shopper_id)
A
select * from orders where shopper_id = 42
plan: Bitmap Heap Scan on orders > Bitmap Index Scan using orders_shopper_idx
rows returned: 10 pages touched: 12
The query for one shopper (10 of 20,000 rows) touches all 148 pages without an index and 12 with one. "Pages touched" is the number of 8 kB pages the plan read, from EXPLAIN (ANALYZE, BUFFERS); unlike timing, it is the same on every run.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
3. An index on a column with few values does not help a query that wants most rows
A (18804 of 20000 rows have this status; the index exists and the planner ignores it)
select * from orders where status = 'delivered'
plan: Seq Scan on orders
rows returned: 18804 pages touched: 148
An index on status exists, yet the planner reads the whole table for 18,804 of 20,000 rows, because fetching nearly everything through an index would cost more than one sequential pass.
Composite indexes: column order is the design
A multicolumn index sorts by its first column, then by the second within equal firsts, and so on. B-tree, GiST, GIN and BRIN support multiple key columns, up to 32 in a default build including included columns. The documentation states the B-tree rule exactly: equality constraints on leading columns, plus any inequality constraints on the first column that does not have an equality constraint, will always be used to limit the portion of the index that is scanned. Constraints on columns to the right are checked inside the index, which saves table visits but does not necessarily shrink the scanned part.
Figure 3. Why the leading column rules. How to read this: entries sit in the order store, then day. "Store 7, days 1 to 3" is one contiguous run, so an equality on the store and a range on the day reads only that run. "Day 2" alone appears once per store, scattered across the whole index.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
4. Composite index: column order decides which queries it serves
index (store_id, placed_on)
A equality on the first column, range on the second
select * from orders where store_id = 7 and placed_on >= date '2026-03-01' and placed_on < date '2026-03-08'
plan: Bitmap Heap Scan on orders > Bitmap Index Scan using orders_store_day_idx
rows returned: 14 pages touched: 9
B only the second column
select * from orders where placed_on = date '2026-03-01'
plan: Seq Scan on orders
rows returned: 100 pages touched: 148
C equality on the first column, ordered by the second, first 5 rows
select * from orders where store_id = 7 order by placed_on limit 5
plan: Limit > Index Scan using orders_store_day_idx
rows returned: 5 pages touched: 7
D same filter, ordered by a column the index does not hold
select * from orders where store_id = 7 order by total_cents limit 5
plan: Limit > Sort > Bitmap Heap Scan on orders > Bitmap Index Scan using orders_store_day_idx
rows returned: 5 pages touched: 150
Query A (equality on store_id, range on placed_on) touches 9 pages through the index. Query B, which filters only on the second column, reads all 148 pages: the planner did not use the index. PostgreSQL 18 added skip scan, which lets a multicolumn B-tree be used when the leading column has no restriction, but the documentation says the planner takes this approach only when there are so few distinct leading values that it expects to skip most of the index; with 50 stores it chose a sequential scan here. Do not design on the hope of a skip scan.
Query C shows the second use of order: with store_id fixed, entries come out sorted by placed_on, so order by placed_on limit 5 reads 7 pages and has no sort node. Query D asks for the same rows ordered by a column the index does not hold, and the plan needs a Sort node and touches 150 pages. The documentation's special case says exactly this: with ORDER BY and LIMIT n, an index matching the order retrieves the first n rows directly, where an explicit sort must process all the data.
Now swap the columns:
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
index (placed_on, store_id)
A equality on store, range on day
select * from orders where store_id = 7 and placed_on >= date '2026-03-01' and placed_on < date '2026-03-08'
plan: Bitmap Heap Scan on orders > Bitmap Index Scan using orders_day_store_idx
rows returned: 14 pages touched: 21
B only the day
select * from orders where placed_on = date '2026-03-01'
plan: Bitmap Heap Scan on orders > Bitmap Index Scan using orders_day_store_idx
rows returned: 100 pages touched: 6
The picture flips. Query B now uses the index and touches 6 pages, but query A, equality on store and a one-week range of days, needs 21 pages instead of 9, because the range on the first column is what limits the scan and the store condition is only a check along the way. Neither order is better; each serves different queries. The documentation advises using multicolumn indexes sparingly: in most cases a single-column index is enough, and more than three columns is unlikely to help.
A mixed ordering such as ORDER BY x ASC, y DESC needs an index declared (x ASC, y DESC) or (x DESC, y ASC); a plain (x, y) serves only the all-forward and all-backward orders.
The query must expose the column
An index on placed_on stores placed_on values. A condition on extract(month from placed_on) compares something the index does not hold, so it cannot narrow the scan. Two cures exist: rewrite the condition as a range on the column, or build an index on the expression itself, as the documentation's lower(col1) example does. An expression index must be computed for each row on insert and non-HOT update, so the documentation calls it relatively expensive to maintain.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
5. A function on the indexed column hides it from the index
A extract(month from placed_on) = 3
select * from orders where store_id = 7 and extract(month from placed_on) = 3
plan: Bitmap Heap Scan on orders > Bitmap Index Scan using orders_store_day_idx
index condition: (store_id = 7)
filter applied to fetched rows: (EXTRACT(month FROM placed_on) = '3'::numeric)
rows returned: 62 pages touched: 150
B the same month as a range
select * from orders where store_id = 7 and placed_on >= date '2026-03-01' and placed_on < date '2026-04-01'
plan: Bitmap Heap Scan on orders > Bitmap Index Scan using orders_store_day_idx
index condition: ((store_id = 7) AND (placed_on >= '2026-03-01'::date) AND (placed_on < '2026-04-01'::date))
rows returned: 62 pages touched: 27
Both queries return the same 62 rows. The function version uses only the store_id part as the index condition and then applies the function as a filter to every row the index returns, touching 150 pages. The range version carries placed_on in the index condition and touches 27.
Covering indexes and index-only scans
An index-only scan answers from the index without visiting the table. It needs two things: the index type supports it (B-tree always does), and the query references only columns stored in the index. The INCLUDE clause adds non-key columns to an index so that more queries qualify. Included columns cannot be searched on, but an index-only scan can return them.
There is a catch. PostgreSQL indexes do not hold tuple visibility information, so the scan checks the table's visibility map, which records whether all rows on a heap page are visible to every transaction. If the bit is set the row is returned from the index; if not, the heap entry must be visited and the advantage is lost. VACUUM maintains the map, and a page modified since the last vacuum loses its bit.
Figure 4. Why an index-only scan can still touch the table. How to read this: the visibility check is the branch. Updated pages take the lower path, which costs a heap visit per entry, as in step 6B below.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
6. Covering index and index-only scans
A after vacuum, every page is all-visible
select placed_on, total_cents from orders where store_id = 7 and placed_on >= date '2026-03-01' and placed_on < date '2026-03-08'
plan: Index Only Scan using orders_cover_idx (heap fetches 0)
rows returned: 14 pages touched: 3
B after updating store 7's rows, before vacuum
select placed_on, total_cents from orders where store_id = 7 and placed_on >= date '2026-03-01' and placed_on < date '2026-03-08'
plan: Index Only Scan using orders_cover_idx (heap fetches 16)
rows returned: 14 pages touched: 22
C after vacuum again
select placed_on, total_cents from orders where store_id = 7 and placed_on >= date '2026-03-01' and placed_on < date '2026-03-08'
plan: Index Only Scan using orders_cover_idx (heap fetches 0)
rows returned: 14 pages touched: 3
A covering index on (store_id, placed_on) include (total_cents) serves the query with an index-only scan and 3 pages. After an update of store 7's rows the same query shows 16 heap fetches and 22 pages: the updated rows sit on pages the visibility map no longer marks all-visible. After vacuum it is back to 0 and 3. The documentation's warning follows: there is little point in including payload columns unless the table changes slowly enough that index-only scans rarely need the heap, and wide included columns bloat the index.
Partial indexes: index only the rows you ask for
A partial index covers a subset of rows chosen by a predicate. The planner can use it only when it can recognise that the query's WHERE implies the predicate; PostgreSQL has no theorem prover, so apart from simple inequalities the predicate must match part of the WHERE exactly, and matching happens at planning time, so parameterized query clauses do not work with a partial index. The main reasons to use one are to avoid indexing common values and to keep the index small, which also speeds up the writes that need not touch it.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
7. Partial index: index only the rows a query asks for
status = 'pending' marks 206 of 20000 rows (about 1%).
A with a full index on store_id
select * from orders where status = 'pending' and store_id = 7
plan: Bitmap Heap Scan on orders > BitmapAnd > Bitmap Index Scan using orders_status_idx > Bitmap Index Scan using orders_store_idx
rows returned: 4 pages touched: 7
B with a partial index on store_id where status = 'pending'
select * from orders where status = 'pending' and store_id = 7
plan: Bitmap Heap Scan on orders > Bitmap Index Scan using orders_pending_store_idx
rows returned: 4 pages touched: 4
C the partial index cannot serve other statuses
select * from orders where status = 'delivered' and store_id = 7
plan: Bitmap Heap Scan on orders > Bitmap Index Scan using orders_store_idx
rows returned: 396 pages touched: 5
Only 206 of 20,000 orders are pending. With a full index on store_id the planner combines it with the status index for 7 pages. A partial index on store_id where status = 'pending' answers the same query in 4 pages, and the next query, for delivered, correctly ignores it. Do not use many partial indexes as a poor man's partitioning: the documentation says the system does not understand the relationship among them and will test each in turn.
What indexes cost
Every index must be kept in step with the table, which adds overhead to data manipulation operations and can prevent heap-only tuples; the documentation's conclusion is that indexes seldom or never used should be removed.
Figure 5. Write amplification. How to read this: one logical insert becomes a table write plus one entry in every index. The partial index only takes the rows that satisfy its predicate, which is part of why it is cheap.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
8. What the indexes cost: pages on disk
orders 150 pages
orders_pkey 57 pages
orders_shopper_idx 25 pages
orders_status_idx 21 pages
orders_store_day_idx 51 pages
orders_cover_idx 81 pages
orders_store_idx 19 pages
orders_pending_store_idx 2 pages
By the end of the lab the table is 150 pages and its seven indexes together are 256 pages: 57 for the primary key, 25, 21, 51, 81 and 19 for the others, and 2 for the partial one. The 81-page covering index is the largest because it carries three columns. Adding an index on a column is not free in storage or in writes, and the partial index shows the cheap end. Building an index has an operational price too: a standard CREATE INDEX locks out writes (not reads) until it finishes, while CREATE INDEX CONCURRENTLY avoids that with two table scans, so it takes longer, and it cannot run in a transaction block.
Build it: measure each effect in pages
This lab is the minimal example, nine numbered steps you can run and change.
Goal. See, with real planner output, when an index is used and when it is ignored, and what each variation costs.
Setup. From the repository's examples/postgres-labs folder:
cd examples/postgres-labs && npm install
node --test labs/btree-indexes/test.mjs
cd labs/btree-indexes && node run.mjs
The first command runs 9 tests; the second prints the nine steps, which is the file examples/postgres-labs/golden/btree-indexes.txt. The helper that measures pages is labs/btree-indexes/lab.mjs.
How it works. createDb builds 20,000 illustrative orders with generate_series and arithmetic, so the data never changes: 2,000 shoppers, 50 stores, 180 days, and pending on every 97th order. measure runs EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) and reports the plan's nodes, rows and shared-buffer hits plus reads, which is stable where timings are not. The tests assert behaviour, not exact counts.
Break it. In test.mjs, in the composite-index test, create orders_store_day_idx on (placed_on, store_id) instead: the assertion that a query on the day alone still reads the whole table fails. Restore the file and re-run.
Stretch. Add (store_id, placed_on desc) and compare; compare pages for date ranges of 1, 7 and 60 days.
What the lab leaves out. Timing, concurrent writers, index bloat, other index types and larger tables. PGlite reports PostgreSQL 19.0 while this course targets 18, so the lesson states only what the 18 documentation also states. Plan choices depend on this data and these statistics: they show the mechanism, not a prediction for your tables.
Choosing an index: the trade-offs
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| No extra index | No write overhead | Every filter scans the table | A query that wants few rows runs often |
| Single-column B-tree | Simple, serves equality, range and order on one column | One more structure to maintain | The column has few distinct values and queries want most rows |
| Composite B-tree | One index serves equality, range and order together | Order is a commitment: the leading column rules | Queries filter on the later columns alone |
Covering (INCLUDE) |
Index-only scans, no table visits | Larger index; useless if pages are often updated | The table changes faster than vacuum can mark pages |
| Partial index | Tiny, cheap writes | Used only when the query implies the predicate | The query passes the predicate as a parameter |
| Expression index | Serves a query on a computed value | Computed on every insert and non-HOT update | A range rewrite of the query would do |
In practice: ShopStream's order history and pending queue
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. The numbers are the lab's illustrative ones.
This is a realistic scenario, not a case history.
The situation
ShopStream shows shoppers their order history, store owners this week's orders, and runs a worker that sweeps pending orders. The three queries are slow, but each new index will also slow every checkout write.
Starting architecture
Figure 6. Three query shapes, three indexes. How to read this: each consumer asks a different question of the same table, and the indexes on the right are what they use. Every write to the table has to maintain all three.
Options considered
| Option | Result | Risk |
|---|---|---|
| A. One index per column | Every filter has an index | Many indexes, each paid for on every write |
B. Composite (store_id, placed_on) plus (shopper_id) |
Covers history and weekly page | The worker's query still scans |
| C. B plus a partial index on pending orders | The sweep reads only pending rows | The sweep query must match the predicate |
The decision
Option C. The shopper index is the lab's step 2, the composite index is step 4A (equality on the store, a range on the day, rows in day order), and the partial index is step 7B. The team writes down why the composite has the store first (every query pins the store) and that the partial predicate is status = 'pending', spelled as a literal.
Rollout and verification
Indexes are built with CREATE INDEX CONCURRENTLY so checkouts keep writing. After each build the team runs ANALYZE and compares each query's plan and pages touched before and after, as the lab does, and watches write latency and index sizes. The change is done when each plan names the new index and the page count has dropped.
The 2 a.m. failure
The page reads: the pending sweeper is slow again. A code change started sending the status as a bind parameter instead of a literal. A partial index is chosen at planning time by checking that the query's condition implies the index predicate, and the documentation says parameterized query clauses do not work with a partial index, so the planner can no longer prove status = $1 implies status = 'pending'. The tiny index is ignored and the sweep reads the full table or a bigger index, as in step 7A.
The check: read the plan for the statement as the application sends it and look for the partial index, then compare with the literal version. The mitigation is to send the literal for this one query. The lasting fix is a test that runs the sweeper's real statement through EXPLAIN and fails if the partial index is missing from the plan.
Architect's notes
- Index for queries, not for columns. List the query shapes first; design the fewest indexes that serve them.
- Put the equality columns first, then the range or sort column. That is the rule the documentation states for what limits the scan.
- Check the plan, not the intention. An index that exists proves nothing; the plan and the pages touched do.
- Treat every index as a write cost. Remove those seldom or never used.
- Covering only for stable pages. Updates erode the visibility map; vacuum restores it.
- Keep partial predicates literal. Match the query's condition exactly.
Common mistakes
- Indexing a column with few values and expecting speed. If the query wants most rows the planner reads the table.
- Reversing the column order "to match the table". The leading column decides what the index serves.
- Wrapping the column in a function. The index holds the column, not the function; rewrite as a range or index the expression.
- Assuming an index-only scan never touches the table. It does when pages are not all-visible.
- Using a parameter against a partial index. Planning cannot match it.
- Adding an index per slow query. Each is paid on every insert and update.
Key takeaways
- A B-tree is a balanced tree of sorted pages; a lookup reads a few pages.
- It serves comparisons,
BETWEEN,IN,IS NULL, an anchoredLIKEand ordered output. - The planner uses an index only when it expects it to be cheaper than a sequential scan; wanting most rows defeats it.
- In a composite index the equality columns and then the first range column limit the scan, so column order is the design.
- A function around the column hides it; rewrite the condition or index the expression.
- A covering index lets an index-only scan skip the table only while pages stay all-visible.
- A partial index is small and cheap but only matches queries that imply its predicate, and not parameters.
- Every index costs writes and disk: the lab's seven indexes take 256 pages against a 150-page table.
Practice exercises
Exercise 1 (20 min). Run the lab. For each of steps 1, 2 and 3, write the plan, the pages touched and why the planner chose it.
Exercise 2 (45 min). Add a query for one shopper's orders in a date range; compare (shopper_id, placed_on) with the separate indexes by pages touched.
Exercise 3 (1 hour). Run "Break it". Then add placed_on desc to the composite index and say which of queries A to D change and why.
Exercise 4 (2 hours). For ShopStream, list five query shapes against orders, design the minimum set of indexes, and write the plan check you would put in CI.
Related reading
- Databases: the basics: the relational model and why indexes exist.
- Storage engines: B-trees compared with LSM-trees.
- ShopStream Stage 3: Choosing the Right Data Store for Each Job: where the orders table lives.
- Aggregation, window functions and CTEs, SQL joins and
EXPLAIN ANALYZEplans are separate lessons in this module.
Official documentation
- PostgreSQL 18, Indexes: introduction and Index types.
- PostgreSQL 18, Multicolumn indexes and Indexes and ORDER BY.
- PostgreSQL 18, Index-only scans and covering indexes and Partial indexes.
- PostgreSQL 18, B-tree implementation and CREATE INDEX.