Sub topic 3
B-tree: the default index and what it supports
This chapter assumes you can read basic EXPLAIN output, as covered in the previous chapter, and that you know SQL well enough to write WHERE, ORDER BY and LIMIT clauses. It covers how a B-tree index is laid out, which operators it supports, how it speeds up ordering, and the mistakes that stop the planner from using it. Multicolumn, partial, expression and covering variants are the next chapter's subject.
Why B-tree is the default
CREATE INDEX with no USING clause builds a B-tree. So do the indexes behind PRIMARY KEY and UNIQUE constraints. PostgreSQL uses a B-tree variant (a B+tree, with all row pointers in the leaf level) because it handles the most common questions a query asks: "find this value", "find values in this range" and "give me rows in this order".
A B-tree works on any data type that has a total ordering, meaning any two values can be compared as less than, equal or greater than. Integers, text, dates, timestamps, UUIDs, numerics and arrays all qualify. Its two strengths are:
- It supports both equality and range comparisons.
- It can return rows already sorted, so a matching
ORDER BYneeds no separate sort step.
How the structure works
An index is stored in the same 8 kB pages as table data. A B-tree has three kinds of page:
- The root page is the single entry point. Its entries are keys that point to child pages.
- Internal pages narrow the search. Each entry says "keys at or above this value live under this child".
- Leaf pages hold the actual index entries. Each entry is a key value plus a tuple identifier (TID), which is the heap page number and row slot where the table row lives.
Leaf pages are linked to their left and right neighbors. That link is what makes range scans cheap. PostgreSQL descends from the root to the first matching leaf, then walks sideways along the leaf level until the range ends.
Each page holds hundreds of entries, so the tree stays shallow. A table with hundreds of millions of rows commonly needs only three or four levels. A lookup therefore reads a handful of pages, while a sequential scan reads every page of the table.
You can see the depth of a real index with the pageinspect extension. Creating it needs superuser rights or an equivalent grant, so treat this as an optional check.
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT level FROM bt_metap('invoices_customer_idx');A level of 0 means the root is also the only leaf. A value of 2 means two internal levels sit between the root and the leaves.
A worked example
The following script builds a one-million-row table, indexes one column and asks the planner for a plan. The table is called invoices so it does not collide with tables in other chapters.
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id integer NOT NULL,
amount numeric(10,2) NOT NULL,
issued_at timestamptz NOT NULL,
note text
);
INSERT INTO invoices (customer_id, amount, issued_at, note)
SELECT (random() * 10000)::int,
(random() * 500)::numeric(10,2),
now() - random() * 365 * interval '1 day',
'invoice ' || g
FROM generate_series(1, 1000000) AS g;
CREATE INDEX invoices_customer_idx ON invoices (customer_id);
CREATE INDEX invoices_issued_idx ON invoices (issued_at);
ANALYZE invoices;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, amount
FROM invoices
WHERE customer_id = 42;Each customer has about 100 rows out of one million, so you should see an Index Scan or a Bitmap Heap Scan fed by Bitmap Index Scan on invoices_customer_idx. The exact node depends on your data and settings. In either case Buffers: should report a few hundred pages at most, instead of the roughly 10,000 pages a sequential scan of this table would read.
Run ANALYZE after bulk loads. The planner chooses plans from column statistics, and without fresh ones it may misjudge how many rows match.
Operators a B-tree supports
A B-tree index with the default operator class serves these comparison operators on its column:
| Operator or construct | Meaning | Uses the index |
|---|---|---|
| `=` | equal | Yes |
| `<`, `<=`, `>`, `>=` | range comparisons | Yes |
| `BETWEEN a AND b` | inclusive range | Yes, rewritten to `>=` and `<=` |
| `IN (a, b, c)` | membership | Yes, treated as several equality probes |
| `IS NULL`, `IS NOT NULL` | null tests | Yes, because B-tree stores NULLs |
| `ORDER BY col` | sorted output | Yes, by scanning leaves in order |
| `min(col)`, `max(col)` | extremes | Yes, by reading one end of the index |
| `LIKE 'abc%'` | left-anchored prefix | Only in the C collation, or with a `text_pattern_ops` index |
| `LIKE '%abc'`, `ILIKE '%abc%'` | substring | No |
| `<>`, `NOT IN` | inequality | Rarely useful, because most rows match |
The prefix LIKE case depends on collation. In a non-C locale, text ordering follows language rules that do not line up with byte-wise prefixes, so the default operator class cannot use a range of keys. The operator classes chapter covers text_pattern_ops, which solves this.
Ordering and LIMIT
Leaf pages are in key order, so an index can answer ORDER BY without a sort. Together with LIMIT, this is often the biggest win:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, issued_at
FROM invoices
ORDER BY issued_at DESC
LIMIT 10;The plan should show an Index Scan Backward using invoices_issued_idx that stops after ten rows. Without the index, PostgreSQL would have to read and sort the whole table, or at best keep a top-10 heap while scanning every row.
A single-column index works in both directions, so ASC or DESC on it rarely matters. Direction becomes important in multicolumn indexes when a query mixes directions, such as ORDER BY a ASC, b DESC.
Sort order of NULLs
By default, ASC puts NULLs last and DESC puts them first. An index can only satisfy an ORDER BY whose NULL placement matches how the index was built. If your query says ORDER BY issued_at DESC NULLS LAST, the default descending index does not match it. You then either create the index to match, as in (issued_at DESC NULLS LAST), or change the query.
Unique indexes
CREATE UNIQUE INDEX and unique constraints are enforced with a B-tree. B-tree is the only built-in index type that can enforce uniqueness, apart from exclusion constraints on GiST, which a later chapter covers. For uniqueness purposes NULLs are treated as distinct from each other by default, so a unique column can hold many NULLs. PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT for the opposite behavior.
When the planner uses an index
Having an index does not force its use. The planner compares estimated costs for each possible plan and picks the cheapest. Several situations make a sequential scan win legitimately:
- The table is small. Reading three pages sequentially costs less than descending a tree and then jumping into the heap.
- The query matches a large share of the table. An index scan reads leaf entries and then fetches heap pages in effectively random order. Once you want something like 5 to 20 percent of the rows, scanning the table in order is cheaper. The exact threshold depends on
random_page_costand on how well the physical row order matches the index order. - The statistics are stale and the planner expects the wrong number of rows.
Intermediate plan shapes you will see:
- Index Scan walks the index and fetches each matching heap row immediately, in index order.
- Bitmap Index Scan plus Bitmap Heap Scan collects all matching TIDs first, sorts them by heap location, then reads the heap pages once each. It is common for mid-sized result sets and it loses the index ordering.
- Index Only Scan answers from the index without reading the heap, when the index holds every needed column and the visibility map says the pages are all-visible. The covering-index section of the next chapter explains how to enable this.
To test whether an index could be used at all, you can temporarily disable sequential scans in a single session:
SET enable_seqscan = off;
EXPLAIN SELECT id FROM invoices WHERE customer_id = 42;
RESET enable_seqscan;Use this only as a diagnostic. If the plan changes and the query becomes faster, the cost settings or statistics need attention. Do not leave the setting off in an application.
Common reasons a B-tree is not used
Most "my index is ignored" reports come from the query, not the index.
A function wraps the indexed column
The index stores issued_at, not issued_at::date. The first query below cannot use invoices_issued_idx. The second asks for the same rows as a range on the raw column, so it can.
-- Cannot use an index on issued_at
SELECT count(*)
FROM invoices
WHERE issued_at::date = DATE '2026-11-01';
-- Can use an index on issued_at
SELECT count(*)
FROM invoices
WHERE issued_at >= TIMESTAMPTZ '2026-11-01 00:00:00+00'
AND issued_at < TIMESTAMPTZ '2026-11-02 00:00:00+00';The cast ::date converts using the session time zone, so the rewritten range must use boundaries in the zone you actually mean. If you really need to filter on a computed value, an expression index (next chapter) is the alternative.
The pattern has a leading wildcard
WHERE note LIKE '%42' cannot use a B-tree, because the start of the string is unknown and the sorted order says nothing about the end. Trigram indexes, which belong to the GIN chapter, handle this case.
The predicate is not selective
A filter such as WHERE amount > 0 matches nearly every row. The planner is right to ignore the index.
The data types do not match
If the constant or parameter has a type that forces a cast on the column side, the index on the raw column is not usable. Compare columns with values of the same type, or cast the constant instead of the column.
A multicolumn index is used out of order
An index on (a, b) is most effective when the query constrains a. A query that filters only on b can sometimes still scan the whole index, but it is rarely efficient. The next chapter covers column order.
Costs to keep in mind
A B-tree is not free. Every INSERT adds an entry to each index on the table, and every UPDATE that changes an indexed column or moves the row to a new heap location adds new entries too. Full pages split in two, which can leave pages partly empty. PostgreSQL leaves 10 percent free space on new leaf pages by default (fillfactor = 90), and since version 13 it deduplicates repeated keys within a leaf page to save space. The final chapters of this tutorial cover size, write cost and maintenance in detail.
Summary of what to remember
- B-tree is the default and supports
=, ranges,IN,IS NULLand ordered output. - It is a shallow tree of 8 kB pages, with sorted, linked leaf pages that hold key and heap-pointer pairs.
- Matching
ORDER BY ... LIMITqueries can stop after a few rows by reading the index in order. - The planner chooses by estimated cost, so small tables and unselective filters correctly use sequential scans.
- Wrapping the column in a function or using a leading wildcard prevents index use.
Exercise
Given an index created with CREATE INDEX invoices_issued_idx ON invoices (issued_at);, which of these queries can use it efficiently, and why? (a) WHERE issued_at >= now() - interval '7 days' (b) WHERE date_trunc('month', issued_at) = TIMESTAMPTZ '2026-11-01' (c) ORDER BY issued_at DESC LIMIT 5 (d) WHERE issued_at IS NULL
Show answer
(a) can use it, because the column is compared directly with a range and the planner can start at one key and walk the leaf pages. (b) cannot, because date_trunc is applied to the column and the index stores raw issued_at values. Rewrite it as a range on issued_at, or create an expression index. (c) can use it through a backward index scan that stops after five rows. (d) can use it in principle, since B-tree indexes store NULLs, but the column in this chapter's table is declared NOT NULL, so the planner would simply know no rows match.
Exercise
A query selects 60 percent of the rows in a table that has a B-tree index on the filter column. EXPLAIN shows a sequential scan. Is something wrong, and how can you check?
Show answer
Probably nothing is wrong. Fetching most of the table through an index means many random heap reads, so a sequential scan is cheaper. To check, run SET enable_seqscan = off; in a session and compare the EXPLAIN (ANALYZE, BUFFERS) timing of the forced index plan against the original plan. Then RESET enable_seqscan;. If the sequential scan is faster, the planner chose correctly.