How B-tree indexes work
Predict whether an index can be used for a given WHERE and ORDER BY.
By Invicly Tech, , in SQL & PostgreSQL. About 12 minutes to read.
In short
A B-tree index is a sorted, balanced tree of key values pointing to table rows. Postgres can walk from the root to the right leaf in a few page reads instead of scanning the whole table, and read leaves in order for sorting.
Think of it like this: Like a book index: jump to "Postgres, page 214" instead of reading every page.
Explained simply
Without an index, Postgres finds rows the slow way: it reads every row of the table and checks each one. That is called a sequential scan. On a table with 10 rows it is instant. On a table with 50 million rows it can take seconds.
An index is a separate, sorted copy of one or more columns, with a pointer from each value back to its row. Because it is sorted, Postgres can jump close to the value it wants, the way you find a word in a dictionary without reading every page.
The default index type in Postgres is the B-tree. It is a short, wide tree of pages. The top page says which page to go to next, and after three or four jumps you reach the bottom page that holds your value. Even for huge tables, that is only a handful of reads.
Indexes are not free. Every INSERT, UPDATE and DELETE must also update every index on the table, and each index takes disk space. So you add indexes for the queries you actually run, not for every column.
Press Play on a diagram to walk through it one step at a time.
- Branch: 1–499
- Leaf: 1–120
- Leaf: 121–260
- Leaf: 261–499
- Branch: 500–999
- Leaf: 500–700
- Leaf: 701–999
- WHERE last_name = 'Lee'
- last_name = 'Lee' AND first_name = 'Al'
- ORDER BY last_name, first_name
- last_name LIKE 'Le%' (with C collation)
- WHERE first_name = 'Al' only
- WHERE lower(last_name) = 'lee'
- last_name LIKE '%ee'
- ORDER BY first_name
- Walk index, then fetch each row
- Rows come out in index order
- Best for very few rows
- Can satisfy ORDER BY + LIMIT
- Collect TIDs, sort by page
- Each table page read once
- Good for hundreds to thousands of rows
- Can combine two indexes (AND / OR)
- Read every page in order
- No index needed
- Best when many rows match
- Can run in parallel
In depth
Inside the tree: pages, fan-out and depth
Postgres stores data in 8 kB pages, and a B-tree index is made of these pages too. Leaf pages at the bottom hold the indexed values in sorted order, each with a pointer called a TID (tuple ID: the table page number and the slot in that page). Upper pages hold only separator keys that say which child page covers which range.
Because one page holds hundreds of keys, the tree is very wide and very shallow. With a few hundred entries per page, three or four levels are enough for hundreds of millions of rows. The upper levels are small and are almost always cached in memory, so a lookup usually costs one or two real disk reads.
Leaf pages are linked to their neighbours in both directions. After finding the first match, Postgres simply walks along the leaves, which is why ranges, ORDER BY and even ORDER BY ... DESC are cheap.
- 1Root page
Separator keys say: go to branch 3
- 2Branch page
Narrows the range: go to leaf 812
- 3Leaf page
Finds the key and its TID (page 4410, slot 7)
- 4Table (heap) page
Reads the row itself
- 5Visibility check
Is this row version visible to my transaction?
When the planner uses an index, and when it doesn't
Having an index does not force Postgres to use it. The planner estimates the cost of each option from table statistics. If a condition matches a small fraction of rows (high selectivity), an index wins. If it matches a large share, say 30 percent of the table, reading the whole table in order is cheaper than thousands of random jumps, so you will see a Seq Scan, and that is correct.
In between, Postgres often picks a Bitmap Index Scan: it collects all matching TIDs from the index, sorts them by page, then reads each table page once.
A B-tree can serve =, <, <=, >, >=, BETWEEN, IN, IS NULL and prefix LIKE 'abc%' (the last one needs the C collation or the text_pattern_ops operator class). It cannot help with LIKE '%abc', with a function wrapped around the column, or with a cast that changes the column's type.
- Few matching rows: Index Scan
- Medium share: Bitmap Index Scan + Bitmap Heap Scan
- Large share: Seq Scan is cheaper
- Functions on the column hide it from a plain index
Composite indexes, the leftmost prefix and ORDER BY
An index on (a, b) is sorted by a first, then by b inside each value of a, like a phone book sorted by last name, then first name. It is very good for WHERE a = ? and WHERE a = ? AND b = ?, and for WHERE a = ? ORDER BY b, because inside one value of a the rows are already in b order. Postgres can then stop after LIMIT rows with no sort at all.
WHERE b = ? alone is the weak case, because matching rows are scattered across every value of a. PostgreSQL 18 added skip scan, which can still use the index when a has only a few distinct values, but the safe rule is still to put the columns you filter by equality first.
Sort direction matters only when you mix directions. ORDER BY a, b DESC needs an index on (a, b DESC). For ORDER BY a DESC, b DESC, the plain index read backwards works.
Index-only scans and the visibility map
A normal index scan reads the index, then visits the table to fetch the row. If every column the query needs is in the index, Postgres can skip the table and answer from the index alone: an Index Only Scan.
There is a catch. The index does not know whether a row version is visible to your transaction; that information lives in the table. Postgres keeps a visibility map, one flag per table page saying "every row here is visible to everyone". Only for those pages can it skip the table. VACUUM sets these flags, so on a table with many recent changes you will see a high Heap Fetches number in EXPLAIN ANALYZE.
You can make an index cover extra columns without sorting by them using INCLUDE (PostgreSQL 11+): CREATE INDEX ON orders (customer_id) INCLUDE (total). The included column is stored in the leaves only.
- Index Only Scan needs every selected column in the index
- Heap Fetches: 0 is the ideal
- VACUUM keeps the visibility map up to date
- INCLUDE adds payload columns to the leaves
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Explain B-tree structure~45m
- 2Know when an index can be used~45m
- 3Match indexes to ORDER BY~45m
- 4See index-only scans~45m
Key points
- Lookups cost about log(n) page reads, even for millions of rows.
- Leaves are linked in sorted order, so ranges and ORDER BY are cheap.
- A function on the column, like lower(col), hides it from a plain index.
- Index-only scans answer from the index alone when all needed columns are in it.
- Every index slows writes slightly and uses disk space.
Key terms
Tap a card to flip it. 0/5 known
Examples
CREATE INDEX customers_name_idx ON customers (last_name, first_name);
-- uses the index (leading column filtered)
SELECT * FROM customers WHERE last_name = 'Lee' ORDER BY first_name;
-- index-only scan possible: every needed column is in the index
SELECT last_name, first_name FROM customers WHERE last_name = 'Lee';
-- plain index not used: wrapped in a function
SELECT * FROM customers WHERE lower(last_name) = 'lee';Watching a plan change when you add an index
Step 1: build a million-row test table with generate_series. Step 2: look up one customer's orders; with no index the plan is a (parallel) Seq Scan that reads every page. Step 3: add an index on customer_id and run ANALYZE. Step 4: the same query now uses a Bitmap Heap Scan or Index Scan and reads only a few pages. Compare the Execution Time lines: typically tens of milliseconds before and well under one millisecond after.
CREATE TABLE orders_demo AS
SELECT g AS id,
(random() * 10000)::int AS customer_id,
now() - g * interval '1 minute' AS created_at,
round((random() * 100)::numeric, 2) AS total
FROM generate_series(1, 1000000) AS g;
ANALYZE orders_demo;
EXPLAIN ANALYZE SELECT * FROM orders_demo WHERE customer_id = 42;
CREATE INDEX orders_demo_customer_idx ON orders_demo (customer_id);
ANALYZE orders_demo;
EXPLAIN ANALYZE SELECT * FROM orders_demo WHERE customer_id = 42;The latest 10 orders of a customer, with no sort
The page "my recent orders" runs WHERE customer_id = ? ORDER BY created_at DESC LIMIT 10. With only an index on customer_id, Postgres fetches all that customer's rows and sorts them. Step 1: create a composite index with the equality column first and the sort column second. Step 2: run EXPLAIN; the Sort node is gone and a Limit sits directly on an Index Scan, which stops after 10 entries. Step 3: because the index also INCLUDEs total and the query selects only columns stored in the index, you get an Index Only Scan.
CREATE INDEX orders_demo_cust_created_idx
ON orders_demo (customer_id, created_at DESC) INCLUDE (total);
VACUUM ANALYZE orders_demo; -- sets the visibility map
EXPLAIN ANALYZE
SELECT created_at, total
FROM orders_demo
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;
-- Limit -> Index Only Scan using orders_demo_cust_created_idx
-- Heap Fetches: 0Quick reference
- CREATE INDEX CONCURRENTLY idx ON t (col); build without blocking writes
- Composite index: equality columns first, then range or ORDER BY columns
- ORDER BY a, b DESC needs an index on (a, b DESC); same directions can read backwards
- LIKE 'abc%' uses a B-tree only with C collation or text_pattern_ops
- CREATE INDEX ON t (a) INCLUDE (b); covering index for index-only scans
- \di+ in psql lists indexes with their sizes
- SELECT indexrelname, idx_scan FROM pg_stat_user_indexes; find unused indexes
Common mistakes
- Indexing every column "just in case", slowing down every write.
- Expecting an index to help when a query matches most of the table.
- Putting the low-selectivity column first in a composite index without reason.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
On orders_demo, create an index that speeds up WHERE created_at >= now() - interval '1 day', then confirm with EXPLAIN that it is used.
- Exercise 2medium
A query runs WHERE status = 'paid' AND customer_id = ? ORDER BY created_at DESC LIMIT 20. Design one index that avoids a Sort node.
- Exercise 3hard
Find indexes in your database that have never been used since statistics were last reset, with their size, largest first. Explain why you should not drop them blindly.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does PostgreSQL index the primary key automatically?
- Yes. PRIMARY KEY and UNIQUE constraints create a unique B-tree index. Foreign key columns are not indexed automatically.
- How many indexes is too many?
- There is no fixed number. Each index slows writes and uses space, so keep the ones your real queries use and check pg_stat_user_indexes for indexes with idx_scan = 0.
- Why is my index not used on a small table?
- For a table that fits in a few pages, a Seq Scan is cheaper than going through an index. This is expected and not a problem.
- Can an index make a query slower?
- A read rarely gets slower because of a new index, but a bad row estimate can lead the planner to a poor index choice. Writes always get a little slower with each extra index.