Sub topic 1
How a B-tree Index Is Searched
This chapter explains how PostgreSQL searches a B-tree index, how to check whether the planner uses one, and why column order matters in a multicolumn index.
Prerequisites
You should know basic SQL (CREATE TABLE, SELECT, WHERE, ORDER BY) and have a PostgreSQL database to test on. Reading EXPLAIN output is helpful but not required.
Use this schema for the examples:
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()
);How a B-tree index is searched
A B-tree stores keys in sorted order across a tree of pages. The search starts at the root page, follows pointers through branch pages, and ends at a leaf page that holds the matching key and a pointer to the table row. Because the tree is sorted, the database needs only a few page reads even for millions of rows.
The index can answer conditions that compare the indexed column with a constant, such as =, <, >, BETWEEN, and IS NULL. It cannot help with a condition that wraps the column in a function unless the index stores that function.
Checking whether the planner uses an index
EXPLAIN shows the plan the planner chose without running the query. Look for Index Scan or Bitmap Index Scan in the output.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;On a small table, the planner may pick a sequential scan because reading the whole table is cheaper. Load realistic data and run ANALYZE orders; before you judge the plan.
Multicolumn indexes
A multicolumn index sorts rows by the first column, then by the second column within each value of the first. The index above sorts by customer_id, then by created_at in descending order.
Why column order matters
A B-tree index works best when the query constrains its leading columns. The index on (customer_id, created_at) can serve a query on customer_id alone, but it cannot serve a query on created_at alone efficiently.
-- Uses the index efficiently: leading column is constrained.
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
-- Usually does not use the index efficiently: leading column is not constrained.
EXPLAIN SELECT * FROM orders WHERE created_at > now() - interval '1 day';Put equality columns first and the sort or range column last.
Exercise
Which index would best serve SELECT * FROM orders WHERE status = 'shipped' ORDER BY created_at; and why?
Show answer
CREATE INDEX ON orders (status, createdat). The equality column status comes first, so the index can find the matching rows, and the rows are already sorted by createdat within each status value.