Sub topic 3
B-tree: the Default Index and What It Supports
Assume you know basic SQL, including SELECT, WHERE, ORDER BY, and LIMIT, and that you can create PostgreSQL tables and insert rows. This chapter focuses on the B-tree access method, PostgreSQL's default index type.
How a B-tree works
A B-tree index stores indexed values in sorted order. Each value points to one or more rows in the table. The tree structure lets PostgreSQL narrow a search by comparing values at each level instead of inspecting every table row.
For example, suppose orders.customer_id contains one million values. Without an index, PostgreSQL may perform a sequential scan:
- Read every row in
orders. - Check whether
customer_id = 42. - Return matching rows.
With a B-tree index, PostgreSQL can navigate directly to the section containing 42, then read the matching entries.
A B-tree is useful when the query compares values using an order. It supports equality, range comparisons, and ordered results.
| Query condition | Typical B-tree support |
|---|---|
| `customer_id = 42` | Direct equality lookup |
| `created_at >= current_date` | Range scan |
| `price BETWEEN 10 AND 20` | Range scan |
| `name LIKE 'Ann%'` | Left-anchored prefix search |
| `ORDER BY created_at` | Reading entries in index order |
Creating and using a B-tree index
PostgreSQL creates a B-tree when you omit the USING clause.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10, 2),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_id_idx
ON orders (customer_id);
SELECT id, total, status
FROM orders
WHERE customer_id = 42;The primary key creates a B-tree index on id automatically. The explicit index supports searches by customer_id.
B-trees also support ranges. PostgreSQL finds the first qualifying index entry and scans forward or backward until the range ends.
CREATE INDEX orders_created_at_idx
ON orders (created_at);
SELECT id, total
FROM orders
WHERE created_at >= timestamptz '2026-01-01 00:00:00+00'
AND created_at < timestamptz '2026-02-01 00:00:00+00';An index can also provide rows in sorted order. This may avoid a separate sort operation.
SELECT id, total, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;An index on only customer_id helps find the rows, but PostgreSQL may still sort those rows by created_at. A multicolumn index can combine the filter and ordering. Choosing its column order is a separate design decision because the order changes which queries it can support efficiently.
Why PostgreSQL may not use the index
Having a suitable index does not force PostgreSQL to use it. The query planner estimates the cost of possible plans and chooses the plan it expects to be cheapest.
For a query that returns most rows, a sequential scan can cost less than an index scan. An index scan may require many random table reads, while a sequential scan reads table pages in order. Small tables also often use sequential scans because starting an index scan has overhead.
Statistics affect this decision. Run ANALYZE after substantial data changes so the planner has current estimates.
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;Look for Index Scan, Index Only Scan, or Bitmap Index Scan in the plan. Index Cond shows a condition used to navigate the index. Filter shows a condition applied after rows were found. With ANALYZE, actual time, row counts, and buffer statistics show what happened during execution, not only what the planner predicted.
Conditions B-trees do not solve well
A normal B-tree is ordered, so it is a poor match for a substring search such as:
SELECT id
FROM users
WHERE email LIKE '%@example.com';The leading wildcard prevents PostgreSQL from identifying a contiguous starting range in the normal sorted order. A prefix pattern such as email LIKE 'admin%' can be indexable, depending on the database collation and operator class.
B-trees also do not naturally index the individual contents of a jsonb document, array, or full-text vector. GIN is usually a better match for those structures. GiST and BRIN serve different data layouts and operators.
Key decisions
Use a B-tree first when the workload contains:
- Equality lookups on scalar values.
- Range conditions such as
<,>=, orBETWEEN. - Left-anchored text prefixes.
- Queries that filter and then order by compatible columns.
- Unique constraints or primary keys.
Before adding one, check the query plan and the expected selectivity. Selectivity is the fraction of rows that match a condition. A highly selective condition usually benefits more from an index than a condition matching most of the table.
Exercise
Why might PostgreSQL choose a sequential scan for SELECT * FROM orders WHERE status = 'open' even when orders(status) has a B-tree index?
Show answer
If most rows have status open, reading the table sequentially may cost less than using the index and fetching many table rows individually. The planner's statistics and cost estimates determine the choice.