Sub topic 4
Point Lookups, Range Scans, and Ordering
This chapter covers what a B-tree index does once the tree exists: find one row, find a run of rows, and return rows in sorted order. It assumes you know basic SQL (SELECT, WHERE, ORDER BY, JOIN), tables with primary keys, and the difference between linear and logarithmic growth. The examples use PostgreSQL syntax.
The three jobs of a B-tree
A B-tree index keeps its keys in sorted order. The leaf level is a chain of pages, and each leaf page points to its neighbors. Almost everything a B-tree does follows from those two facts:
- Point lookup: descend from the root to one leaf entry that matches an exact key.
- Range scan: descend to the first matching key, then walk the leaf pages sideways until the range ends.
- Ordered retrieval: because leaf entries are already sorted, reading them in order produces sorted output without a separate sort step.
Point lookups
A point lookup uses an equality predicate on the indexed column. Using the orders table from this tutorial:
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;The engine starts at the root page and compares 42 with the separator keys to pick a child. It repeats this at each level until it reaches a leaf. Inside the leaf, it finds the first entry equal to 42. Each entry holds the key plus a pointer to the table row, so the engine then fetches that row from the table.
The cost is the tree height, not the table size. Real B-trees are wide: one 8 KB page holds hundreds of keys, so a tree with a few hundred million rows is often only three or four levels deep. Going from a million rows to a hundred million adds about one level. That is the logarithmic growth you were assumed to know.
Two details matter for correctness and performance:
- Non-unique indexes can return many entries.
customer_idis not unique. The lookup finds the first42and keeps reading adjacent leaf entries until the key changes. A "point lookup" on a non-unique column is really a very short range scan. - Each match costs a table fetch. The index entry says where the row is, but the columns you selected live in the table. For a customer with 5,000 orders, that is 5,000 table fetches, often at scattered locations on disk. Chapter material on selectivity and covering indexes returns to this cost.
Range scans
A range predicate uses <, <=, >, >=, BETWEEN, or a prefix match such as LIKE 'abc%' (the prefix form needs a suitable operator class or the C collation in PostgreSQL). The engine does one descent to the lower boundary, then follows the leaf chain until it passes the upper boundary.
CREATE INDEX orders_created_at_idx ON orders (created_at);
SELECT id, total_cents
FROM orders
WHERE created_at >= '2026-01-01'
AND created_at < '2026-02-01';The work is one descent plus a number of leaf pages proportional to the number of matching entries. Cost is roughly O(log n + k), where k is the number of matches. Two consequences follow:
- A narrow range is cheap. A range covering most of the table is not, because k approaches n and every match still needs a table fetch.
- Half-open ranges (
>= start AND < end) avoid double counting boundaries. They also keep the column bare, which keeps the predicate usable by the index. A later chapter covers this under index-friendly predicates.
Equality followed by a range
With a composite index, the engine can combine an equality on the first column with a range on the second. This is the pattern that composite indexes handle best.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at);
SELECT * FROM orders
WHERE customer_id = 42
AND created_at >= '2026-01-01';Within the index, all entries for customer 42 sit together, sorted by created_at. The engine descends straight to (42, '2026-01-01') and reads forward until customer_id changes. A range on the first column ends the useful ordering. Once the first column varies across the scanned range, the second column is no longer sorted across that whole range.
Ordering for free
Because leaf entries are sorted, an index can satisfy ORDER BY without a sort. Without a matching index, the engine reads the rows and sorts them. That costs O(n log n) time and memory, and it spills to disk when the data exceeds the sort memory limit. With a matching index, rows arrive in order and the engine can stop early.
SELECT id, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;With orders_customer_created_idx, the engine finds the entries for customer 42 and reads them from the end, newest first. B-trees can be read in either direction, so DESC needs no separate index. After ten entries the scan stops. The cost does not depend on how many orders customer 42 has. Without the index, the engine must fetch and sort all of that customer's orders before it can return ten.
This "top-N" pattern is one of the most valuable uses of an index. It underlies paginated lists, "latest events" feeds, and "most recent per user" queries.
When the order does match
An index can supply order when the ORDER BY columns line up with the index columns, with these rules:
| Query | Index | Sort avoided? |
|---|---|---|
| `ORDER BY created_at` | `(created_at)` | Yes |
| `WHERE customer_id = 42 ORDER BY created_at` | `(customer_id, created_at)` | Yes, equality column is fixed |
| `ORDER BY customer_id, created_at` | `(customer_id, created_at)` | Yes |
| `ORDER BY created_at` | `(customer_id, created_at)` | No, first column varies |
| `ORDER BY customer_id, created_at DESC` | `(customer_id, created_at)` | Not directly, mixed directions |
The last row has a fix. You can declare per-column direction, which makes the index order match the query.
CREATE INDEX orders_customer_created_desc_idx
ON orders (customer_id ASC, created_at DESC);Mixed directions are the only case where direction matters. A fully ascending index serves a fully descending ORDER BY by reading backward.
NULL placement
PostgreSQL sorts NULL as larger than any value by default: last in ascending order, first in descending order. If your ORDER BY uses NULLS FIRST or NULLS LAST against that default, the index must be declared with the same choice, such as (created_at DESC NULLS LAST). Otherwise the planner cannot use it to avoid a sort. Other databases choose different defaults, so check yours.
Seeing the difference in a plan
EXPLAIN shows whether the engine used the order. Look for a Sort node.
EXPLAIN
SELECT id, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;With the composite index in place, the plan has Index Scan Backward using orders_customer_created_idx under a Limit node, and no Sort. Without it, you typically see Sort above a scan with Sort Method details when you run EXPLAIN ANALYZE. The exact text varies by version and data, so read the node types, not the numbers.
Edge cases and common errors
- Returning most of the table. If a range matches a large fraction of rows, the planner usually prefers a sequential scan. Reading the table once in order beats thousands of random fetches. This is correct behavior, not a missing index.
- Sorting on a different column than you filter. An index on
(customer_id)finds customer 42's rows but does not order them bycreated_at. The engine still sorts. - Range on an earlier column. With
(created_at, customer_id), the queryWHERE created_at >= '2026-01-01' AND customer_id = 42scans every entry in the date range and filters oncustomer_idas it goes. Put equality columns first and the range column last. - Deep pagination with
OFFSET.OFFSET 100000 LIMIT 10still walks past 100,000 index entries. Keyset pagination avoids this by seeking to the last seen key, as inWHERE (customer_id, created_at) < (42, '2026-03-01') ORDER BY .... - Collation. Text indexes sort by the column's collation. A query using a different collation, or an
ORDER BYthat differs from the index's, cannot reuse it.
Summary of the model
- A point lookup costs one tree descent. On a non-unique key it continues through adjacent equal entries.
- A range scan costs one descent plus the leaf pages that hold the matches.
- Sorted leaves let the engine skip
ORDER BYsorts and stop early underLIMIT. - Every matching entry usually costs a table fetch, so cost grows with the number of matches.
Exercise
A table has the index (customer_id, created_at). For each query, say whether the index can avoid a sort, and why. (a) WHERE customer_id = 7 ORDER BY created_at DESC LIMIT 5. (b) WHERE created_at >= '2026-01-01' ORDER BY created_at.
Show answer
(a) Yes. The equality on customerid fixes the first column, so entries for customer 7 are sorted by createdat. The engine reads them backward and stops after 5 rows. (b) No. customerid is not constrained, so createdat is not sorted across the whole index. The engine needs a separate index on created_at, or a sort.
Exercise
Why can a range query matching 60% of a table be slower with an index than without one?
Show answer
Each matching index entry normally requires a fetch from the table, often at scattered locations. For a large share of rows, thousands of random fetches cost more than reading the table once sequentially. The planner then correctly chooses a sequential scan.