Sub topic 1
How a B-tree Index Is Searched
A B-tree index is the default index type in PostgreSQL. Every later chapter builds on it: multicolumn, partial, and expression indexes are all B-trees with a different choice of what goes into them. This chapter explains how a search walks the tree, which conditions it can use, and how to check that PostgreSQL actually uses it.
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL:
SELECT,WHERE,ORDER BY, andCREATE TABLE. - Explain what an index is and why it speeds up lookups.
- Run
EXPLAINand read the first lines of its output. Experience here helps, but the chapter explains what you need.
The examples use two tables that all later chapters share.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total_cents integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
deleted_at timestamptz
);The shape of a B-tree
A B-tree stores key values in sorted order, spread across fixed-size pages (8 kB by default). The pages form a tree with three kinds of node:
- The root page is the single entry point.
- Internal pages hold keys and pointers to child pages. Each key marks a boundary between the key ranges of two children.
- Leaf pages hold the indexed key values and, for each one, a pointer to a row in the table. This pointer is called a tuple identifier (TID). It names the table page and the row's position within it.
The table itself is called the heap. Rows in the heap are not stored in key order. The index is what gives you sorted access.
Leaf pages are also linked to their neighbors in both directions. This detail matters for range scans and for ORDER BY, as the next sections show.
Descending the tree
Suppose you create a single-column index and run an equality query.
CREATE INDEX orders_customer_idx ON orders (customer_id);
SELECT * FROM orders WHERE customer_id = 42;The search proceeds in four steps:
- Start at the root page. Compare 42 against the keys on the page to pick the child whose range contains 42.
- Repeat at each internal page until you reach a leaf page.
- On the leaf page, find the first entry with key 42.
- Read entries in order while the key is still 42. For each one, fetch the row from the heap using its TID.
Each page is searched by binary search, and the tree is shallow because each page holds hundreds of keys. A table with hundreds of millions of rows typically needs only three or four levels. So finding the first match costs a handful of page reads, regardless of table size. The cost grows with the number of matching rows, because each match is another entry to read and usually another heap page to visit.
Which conditions a B-tree can use
The tree can answer any question that maps to a contiguous range of the sorted keys. These operators work on a B-tree:
<,<=,=,>=,>BETWEEN, which is shorthand for two comparisonsIN (...)and= ANY (...), which become several lookups in one scanIS NULLandIS NOT NULL. PostgreSQL stores NULLs in B-tree indexes, so this is supported.
A range condition works the same way as equality. The search descends to the first qualifying entry, then walks along the linked leaf pages until the keys stop qualifying.
-- Descend to the first id >= 1000, then walk right until id > 2000.
SELECT id, status
FROM orders
WHERE id BETWEEN 1000 AND 2000;Because the leaf pages are linked in both directions, the same walk can run backward. That is how an index supports ORDER BY ... DESC without any extra structure.
Pattern matching
LIKE 'abc%' is a range in disguise: it means "keys from abc up to just below abd". The B-tree can use it only if the index sorts text the same way that range requires. That holds when the index uses the C collation or the text_pattern_ops operator class. With most other collations, the sort order does not match a plain prefix range, so the index is skipped. A pattern with a leading wildcard, such as LIKE '%abc', does not map to a contiguous range, so a B-tree cannot help.
What a B-tree cannot use
A condition is a poor fit when it does not describe a contiguous range of the indexed key. Common cases:
- A function wrapped around the column. The index holds
email, notlower(email). The conditionWHERE lower(email) = '[email protected]'asks for a value the index never stored. The expression index chapter covers the fix. - Arithmetic on the column.
WHERE total_cents + 100 = 5000has the same problem. Rewrite it asWHERE total_cents = 4900when you can. - A leading wildcard in
LIKE, as above. - Negation.
WHERE status <> 'shipped'selects everything outside one value. If most rows match, the index offers no advantage. - A mismatched type that forces a cast on the column side. Compare a column to a value of the column's own type.
A condition that passes this list is necessary but not sufficient. The planner still has to judge whether the index is worth using.
Index scans, bitmap scans, and sequential scans
The planner chooses among access methods by estimated cost. It uses table statistics to guess how many rows a condition will return.
| Access method | How it works | Typically chosen when |
|---|---|---|
| Index Scan | Walks the index and fetches each heap row as it goes. Returns rows in index order. | Few rows match, or the query needs index order. |
| Bitmap Index Scan with Bitmap Heap Scan | Collects all matching TIDs, sorts them by heap page, then reads each page once. | A moderate number of rows match. |
| Seq Scan | Reads the whole table in order. | Many rows match, or the table is small. |
Heap fetches are the expensive part of an index scan. They land on scattered pages, which means random reads. If a condition matches, say, 30% of the table, reading every page once in order is usually cheaper than making that many random visits. PostgreSQL will choose a sequential scan in that case, and that is the correct choice.
Checking whether the index is used
Run EXPLAIN to see the plan the planner picked. The following is a sketch of what to expect for the index created earlier, on a large table:
EXPLAIN
SELECT * FROM orders WHERE customer_id = 42;Bitmap Heap Scan on orders (cost=4.45..62.10 rows=20 width=40)
Recheck Cond: (customer_id = 42)
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..4.44 rows=20 width=0)
Index Cond: (customer_id = 42)Read the plan from the innermost line outward. The Index Cond line shows the condition that the B-tree search itself used. If you see Seq Scan on orders instead, the index was not chosen.
Several reasons lead to that result:
- The table is small, so a full read is cheaper than any index descent.
- The condition matches a large share of the rows.
- Statistics are stale, so the planner's row estimate is wrong. Running
ANALYZE orders;refreshes them. - The condition has one of the shapes listed in the previous section.
Do not assume that a missing index scan means something is broken. Test on data that resembles production in size and distribution, because plans on a tiny development table often differ.
Edge cases to keep in mind
- Duplicates are fine. A non-unique B-tree stores equal keys next to each other, so an equality search reads them as one contiguous run.
- NULLs sort at one end. By default they sort after all non-null values in ascending order. This affects
ORDER BYsupport, which a later chapter covers. - Index entries can point to dead rows. After an
UPDATEorDELETE, old row versions remain in the heap until vacuum removes them. The search may visit them and discard them. This is one reason regular vacuuming matters for index performance. - Primary keys and unique constraints already create a B-tree. The
idcolumns in the running schema are indexed without any extra statement.
Exercise
The table users has a B-tree index on email. Why does SELECT id FROM users WHERE lower(email) = '[email protected]' not use it, and why might SELECT id FROM users WHERE email = '[email protected]' still use a sequential scan on a table with 50 rows?
Show answer
The index stores the raw email values in sorted order. The condition on lower(email) asks for a computed value that the index never stored, so the tree cannot be descended to find it. The second query matches the index, but on a table with 50 rows the whole table fits in one or two pages. The planner estimates that reading them directly costs less than descending the tree and then fetching from the heap, so it picks a sequential scan.
Exercise
A query returns about 40% of the rows in a large table through an indexed range condition. The planner chooses a sequential scan. Is this a problem? Give the reason.
Show answer
No. An index scan makes a heap fetch for each matching row, and those fetches hit scattered pages with random reads. With 40% of the rows matching, reading every table page once in order is cheaper. The planner is correct to skip the index.