How a B-Tree Index Finds Your Rows
See how a PostgreSQL B-tree turns a full-table scan into a four-page descent, when the planner refuses to use one, and what every index costs your writes.
Contentsand lesson path
On this page
- Why it matters
- Inside a B-tree
- Sequential scan or index: the planner decides
- Answering from the index alone, and the bill for writes
- Check your understanding
- Apply it
- Review prompt
Lessons of Indexing & Query Optimization
- How a B-Tree Index Finds Your Rows Concept · 20 min
- Reading an Execution Plan Node by Node Worked example · 30 min
- Lab: Designing Indexes for a Workload, Text Search Included Lab · 30 min
- Index-Friendly Rewrites and Fresh Statistics Lab · 25 min
- Finding the Queries That Actually Matter Lab · 20 min
- Check: Diagnose Three Slow Queries Knowledge check · 8 questions
What you will learn
- Choose B-tree, composite, partial, covering or expression indexes (and recognize when GIN or BRIN fit, including GIN for full-text and trigram search) for a query pattern, accounting for write overhead.
Prerequisites: SQL Fundamentals
01. Why it matters
You already write SQL: filtering, joining and grouping from the SQL fundamentals skill. Then one day a query that felt fine takes seconds, and someone tells you to add an index. Adding one is a single line of SQL. Knowing which index, when it helps, and what it costs is the difference between that advice working and quietly making the system slower.
This lesson opens that black box. You will look inside a real B-tree, watch the planner choose between a sequential scan and an index, see why an index on the wrong column changes nothing, and learn the bill every index hands to every INSERT, UPDATE and DELETE. The query plans here come from PostgreSQL 17, but the ideas apply to MySQL, SQLite and SQL Server too, because they all build their indexes as B-trees (some, like MySQL InnoDB and SQLite, store the table rows in one too) for the same reason: discs and memory both read pages, and a sorted tree of pages finds one key among millions in a handful of page reads.
02. Inside a B-tree
A B-tree index is a sorted, balanced tree of fixed-size pages (8 kB in PostgreSQL). Leaf pages hold the indexed keys in order, each key next to a pointer to the row (its TID: the heap page number and the item's slot on that page, which you can see as the hidden ctid column, for example (0,1)). Internal pages hold nothing but keys and child pointers. The tree is balanced, so every descent from root to leaf visits the same number of pages, and pages split as they fill, so the tree stays shallow: one or two levels for a million keys, three for hundreds of millions.
Start a lab container and a small demo table so you can see a real one. This container is the same one the rest of the skill uses, and it preloads the pg_stat_statements library that the last lesson needs, with planning-time tracking switched on (track_planning is off by default):
docker run -d --name qopt-lab \
-e POSTGRES_USER=lab -e POSTGRES_PASSWORD=lab \
-p 127.0.0.1:55461:5432 postgres:17-alpine \
-c shared_preload_libraries=pg_stat_statements \
-c pg_stat_statements.track_planning=on
docker exec -it qopt-lab psql -U lab -d labCREATE DATABASE qopt;
\c qopt
CREATE EXTENSION pgstattuple;
CREATE TABLE demo_orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL
);
SELECT setseed(0.42); -- fixed seed: your rows match this page
INSERT INTO demo_orders (customer_id, status, total, created_at)
SELECT (random() * 49999)::int + 1,
CASE WHEN r < 0.015 THEN 'pending'
WHEN r < 0.06 THEN 'cancelled'
WHEN r < 0.25 THEN 'shipped'
ELSE 'completed' END,
round((random() * 480 + 9.90)::numeric, 2),
timestamptz '2025-01-01' + (random() * 669) * interval '1 day'
FROM (SELECT g, random() AS r FROM generate_series(1, 200000) g);
ANALYZE demo_orders;The setseed call fixes the random number generator for the session, so your table holds exactly the rows used on this page and your row counts will match the outputs below. Timings will not: they depend on your machine, which is why every output that prints them is marked Illustrative.
Now fetch a single order by primary key, then inspect the index that served it:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM demo_orders WHERE id = 12345;Index Scan using demo_orders_pkey on demo_orders
(cost=0.42..8.44 rows=1 width=39)
(actual time=0.091..0.092 rows=1 loops=1)
Index Cond: (id = 12345)
Buffers: shared hit=3 read=4
Planning Time: 1.184 ms
Execution Time: 0.209 mspgstatindex from the pgstattuple extension reports the physical shape of a B-tree:
SELECT tree_level, index_size, root_block_no, leaf_pages,
avg_leaf_density
FROM pgstatindex('demo_orders_pkey'); tree_level | index_size | root_block_no | leaf_pages | avg_leaf_density
------------+------------+---------------+------------+------------------
2 | 4513792 | 412 | 547 | 90
(1 row)Read the two together. The index has 547 leaf pages under a root that sits two levels above them (tree_level 2): root, one band of internal pages, leaves. To find id = 12345 the engine read the root (one page), one internal page (one more), one leaf page (a third), then followed the TID to the heap page holding the row: four pages on the descent. BUFFERS counts every buffer access, so shared hit=3 read=4 is seven accesses in total — three pages already in shared buffers and four fetched from the operating system. (How the seven split between hit and read depends on what is already cached; straight after the load, all seven often show as hits.) The extra three are one-off work for the first lookup in a session, such as reading the index metapage that tells PostgreSQL where the root is (the backend then caches it). Run the same query again in the same session and the line drops to shared hit=4: exactly the descent. That is the whole trick. Doubling the table adds at most one level, so the descent grows logarithmically while a sequential scan grows with row count. The Index Cond line matters too: the comparison happened inside the index, so only matching keys came out.
03. Sequential scan or index: the planner decides
An index is not a promise; it is an option the planner prices. A sequential scan reads every page of the table once, in order, which is cheap per page. An index scan jumps straight to matching keys but then chases a heap pointer per row, and random page reads cost more than sequential ones. So the planner estimates what fraction of the table a predicate matches — the selectivity — and picks accordingly.
Watch it happen. Ask for one customer's orders from the demo table before any secondary index exists:
EXPLAIN (ANALYZE)
SELECT * FROM demo_orders WHERE customer_id = 1234;Seq Scan on demo_orders (cost=0.00..4326.00 rows=5 width=39)
(actual time=1.289..17.097 rows=3 loops=1)
Filter: (customer_id = 1234)
Rows Removed by Filter: 199997
Planning Time: 0.726 ms
Execution Time: 17.173 msThe engine read all 200,000 rows and threw 199,997 of them away. Add the index and repeat:
CREATE INDEX demo_orders_customer_idx ON demo_orders (customer_id);
ANALYZE demo_orders;
EXPLAIN (ANALYZE)
SELECT * FROM demo_orders WHERE customer_id = 1234;Bitmap Heap Scan on demo_orders (cost=4.46..23.74 rows=5 width=39)
(actual time=0.076..0.080 rows=3 loops=1)
Recheck Cond: (customer_id = 1234)
Heap Blocks: exact=3
-> Bitmap Index Scan on demo_orders_customer_idx
(cost=0.00..4.46 rows=5 width=0)
(actual time=0.069..0.070 rows=3 loops=1)
Index Cond: (customer_id = 1234)
Planning Time: 0.369 ms
Execution Time: 0.126 msSame answer, 17 ms down to 0.13 ms. Two new node types appeared: a Bitmap Index Scan node builds a map of heap pages containing matches, and the Bitmap Heap Scan node then reads those pages in one pass, sorting the random reads into something closer to sequential. For a handful of rows the planner sometimes skips the bitmap and does a plain Index Scan, walking the B-tree and the heap key by key; both shapes appear throughout this skill, and the next lesson reads them node by node.
Now the counter-example. Three quarters of the rows are completed. Give status an index of its own, so the planner really has the choice, and ask for those rows:
CREATE INDEX demo_orders_status_idx ON demo_orders (status);
ANALYZE demo_orders;
EXPLAIN (ANALYZE)
SELECT * FROM demo_orders WHERE status = 'completed';Seq Scan on demo_orders (cost=0.00..4326.00 rows=149400 width=39)
(actual time=0.012..22.981 rows=150022 loops=1)
Filter: (status = 'completed'::text)
Rows Removed by Filter: 49978
Execution Time: 27.276 msThe planner ignored the index on purpose. Reading 75% of the table through index pointers means touching most heap pages anyway, plus the index pages: more work than just reading the table once. A rule of thumb survives contact with real planners: an index earns its keep when a query needs a small fraction of a large table — single-digit percentages, fewer rows than a few percent of the table, or a LIMIT that can stop early. The same query on status = 'pending' (1.5% of rows, 2,953 orders) switches to a bitmap scan and finishes in a few milliseconds.
04. Answering from the index alone, and the bill for writes
If every column a query needs lives in the index, the heap visit disappears: an Index Only Scan reads leaves and stops there. The catch is visibility. PostgreSQL must prove that the index entry matches a row version the query is allowed to see, and that proof lives in the heap page — unless the visibility map says the page contains only rows visible to everyone, which VACUUM maintains. After a bulk load, VACUUM first, then:
VACUUM (ANALYZE) demo_orders;
EXPLAIN (ANALYZE)
SELECT count(*) FROM demo_orders
WHERE customer_id BETWEEN 100 AND 200;Aggregate (cost=13.60..13.61 rows=1 width=8)
(actual time=0.077..0.077 rows=1 loops=1)
-> Index Only Scan using demo_orders_customer_idx on demo_orders
(cost=0.42..12.58 rows=408 width=0)
(actual time=0.019..0.056 rows=409 loops=1)
Index Cond:
((customer_id >= 100) AND (customer_id <= 200))
Heap Fetches: 0
Execution Time: 0.113 msHeap Fetches: 0 is the healthy sign: no heap pages at all. This is why covering indexes and the INCLUDE clause exist — a topic the index design lab takes up properly.
Finally, the bill. That demo table is 14 MB of heap; its three B-trees (primary key, customer_id, status) together are about 8 MB, more than half the table again, sitting beside it permanently. And every index is maintained on every write: an INSERT inserts a row and an entry into each index (a partial index only when the row matches its WHERE); an UPDATE that touches an indexed column writes a new row version and new index entries. In the index design lab, bulk-loading 100,000 rows into a copy of the orders table that carries three secondary indexes ran noticeably slower than a bare copy (under half its rate on the run shown there). The lab lets you measure it on your own hardware: the exact numbers differ from machine to machine, but more indexes mean more work per written row. So an index is a bet: you pay a tax on every write and a slice of storage, and you collect only when queries actually match the index shape. Indexes that match nothing are pure loss, which is why dropping unused indexes is as much a part of optimisation as adding them.
05. Check your understanding
06. Apply it
In the qopt database, list every index on demo_orders with \d demo_orders, and for each one write one sentence: which query shape it serves, and roughly what fraction of rows that shape matches. Then run EXPLAIN (ANALYZE) on three of those shapes and check whether the planner agreed with you. Keep the container running: the next lesson loads the full shop dataset into it and reads real execution plans.
07. Review prompt
Without looking back: describe the page reads a primary-key lookup performs from root to heap page. Explain, with the two status queries, why the planner sometimes refuses a perfectly good index. And state the two costs every additional index imposes on a table that receives writes.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.