Relational databases: collection tree

Relational databases

Indexes and access paths

Deep diveAbout 16 minutes AI-generated

An index is a separately maintained route to rows. A table scan finds one customer's orders by testing the table's rows. An index on customer ID puts that customer's entries together and records how to find their rows. A useful index makes the search smaller, supplies an order the query needs, or holds values that would otherwise require a table fetch.

Those are different savings. An index can find the right customer and still fetch thousands of orders to sort ten of them. It can avoid a sort while passing thousands of other customers' entries. It can hold every returned value and still need the table to check which row versions the reader may see. Choosing an index means identifying which work it removes.

The shop's customer-history screen asks for ten orders, newest first, since a chosen time. We will derive its index from that request, then compare it with paid-only history, order-line lookups and a broad report. The small examples use twelve selected rows from the collection's generated history, with invented physical page layouts. The measured comparison uses the complete fixture of 120,003 orders. The SQL is PostgreSQL's; the main ideas apply to ordered B-tree indexes in other relational engines too.

Index entries and table rows

An index entry holds a key and a row locator. For an index on customer_id, the key is the customer ID. The locator is what the engine needs to find the corresponding row. In a PostgreSQL heap, where table rows are not maintained in key order, it identifies a table page and a slot on that page.

The entries themselves occupy index pages. A B-tree arranges those pages into a shallow search tree. Its bottom pages, the leaves, hold the ordered entries. Pages above them direct a search towards the leaf whose range contains the desired key. The top page is the root. Suppose a small two-level tree holds customer 1001’s four entries on one leaf. A lookup reads the root, chooses that leaf and obtains four row locators.

Adjacent entries, scattered rows
Figure 1. Twelve selected fixture rows, arranged on four invented table pages. Each leaf has room for four entries here; real pages hold many more. The locators and page counts belong to this drawing, not the measured database.
Figure as text

Customer 1001 follows the root to one leaf. Its four adjacent entries point to four separate table pages. The search visits two index pages and four table pages; it does not reorder the table.

That lookup visited two index pages. If the four referenced rows occupy four different table pages, fetching them visits all four. The entries sit together; the table rows need not. Reading neighbouring leaves continues a range without starting again at the root, but fetching each selected row is another kind of work.

A larger tree usually grows wider before it grows deeper: each branch directs searches to many child pages. A lookup therefore needs few index pages even in a large table. The range after that lookup can still be enormous. Finding the first of 80,000 entries quickly does not make reading the next 79,999 free.

In a clustered table, such as an InnoDB table with a primary key, the table rows live in the leaves of the key’s tree. Another index carries that primary key as its row locator. Finding an order through its customer index then starts a second search in the table’s tree for the order ID. This differs from a heap’s page-and-slot locator; it also makes the clustered key’s width a cost in every secondary index.

Column order in a composite index

The history query supplies three kinds of information: one customer, a lower time bound and a requested order. It also needs status for display:

SELECT order_id, placed_at, status
FROM orders
WHERE customer_id = 1001
  AND placed_at >= timestamptz '2026-10-01 00:00+00'
ORDER BY placed_at DESC, order_id DESC
LIMIT 10;

A composite, or multicolumn, index sorts by its first key column, then by the second within equal first values, and so on. The index (customer_id, placed_at DESC, order_id DESC) groups one customer's orders, puts the newest first within that group and breaks equal-time ties by descending ID.

For a smaller comparison, ask for two results from twelve selected orders: four each for customers 1001, 1002 and 1003. Customer 1001 has one August order and three since October. Keep those rows fixed while comparing customer-only, customer-leading time-and-ID, and time-leading indexes.

Three keys for the same history request
Figure 2. A hand trace over the same twelve selected rows, customer 1001, lower bound 1 October 2026, LIMIT 2. Dates are UTC and every selected timestamp is at noon. Counters describe this trace; they are not native EXPLAIN fields.
Figure as text

The same twelve entries are arranged by the selected key. Customer only examines and fetches four rows, sorts three eligible rows, then returns two. Customer then time examines and fetches two. Time first examines six entries and fetches two. Every route returns orders 100003 and 100042.

Customer alone finds four entries, but supplies neither their dates nor the required order. Four row fetches leave three eligible orders to sort. Customer, then time and ID finds the first two eligible entries in order and stops. Time first encounters other customers along the way: six entries produce two row fetches. Checking the customer inside that index avoids fetching the other four rows, but does not make those four entries disappear from this traversal.

This gives a useful starting rule for B-tree design: equality on leading key columns, followed by a range on the next column, defines a contiguous search interval. In the history key, customer equality selects one run and the time bound selects its recent end. A condition on a later key can reject entries inside that interval without necessarily shortening it. Engines can sometimes use repeated searches or a skip scan to avoid parts of such a traversal; the chosen route and its cost remain implementation dependent.

Where a status condition belongs

Suppose paid-only history adds status = 'paid'. Leading with (customer_id, status, placed_at DESC, order_id DESC) gives that query one paid run already in time order. But all-status history now has separate paid, pending and cancelled runs. Their union is not one newest-first list. Putting status after the ordering columns preserves that list, while generally leaving paid entries interleaved with other statuses.

When two columns are both fixed by equality, either order can locate their joint values. Choose their order by the other queries too. Customer first supports customer history without a status condition; status first supports status-wide requests without a customer condition. “Put the most selective column first” does not answer that workload question.

ORDER BY and stopping at LIMIT

The ordered history key can save more than a sort. Once it has supplied ten eligible orders, every later entry for this customer is older, or has a smaller ID at the same time. The query can stop asking. If an unindexed status test rejects rows, it must keep going until ten pass or the range ends.

CREATE INDEX orders_history
ON orders (customer_id, placed_at DESC, order_id DESC);

The ID is part of the requested order, even when a small example happens to have different timestamps. The generated fixture has many same-time orders. Keeping the ID in both SQL and the key gives a predictable order within those ties. The key can also support a continuation bound for keyset pagination; Pagination and consistent exports derives that bound and explains what changes between reads can still do.

A B-tree can be read in reverse. With customer fixed, an ascending time-and-ID suffix can supply descending time and descending ID backwards. Reversing a scan reverses all the varying directions together. A request for time descending but ID ascending therefore needs a matching mixed order, or additional sorting.

Null placement and text collation matter as well. PostgreSQL's default ascending order puts nulls last; its reverse puts them first. The two history ordering fields are non-null, so that choice is absent here. For a nullable or textual sort, match the query's null placement and comparison rules to the index. Keep ORDER BY in the SQL: the index makes the promised order cheaper; its presence does not promise it.

The report in Query execution and performance asks a different question: the customers with the largest paid-order line values. Adding LIMIT 10 after those totals does not let an ordinary order-date index stop after ten orders. The last contributing line could change the winning total. An early stop needs an input order that proves what can no longer affect the answer.

Match the query to the indexed value

The history bound compares a timestamp directly with a timestamp. An index on placed_at stores that ordering. A query that first transforms every timestamp into a calendar date is asking about another value:

-- Direct bounds on the stored timestamp.
WHERE placed_at >= timestamptz '2026-10-01 00:00+00'
  AND placed_at <  timestamptz '2026-10-02 00:00+00'

-- A comparison on a derived UTC date.
WHERE (placed_at AT TIME ZONE 'UTC')::date
      = date '2026-10-01'

These predicates select the same UTC day, but do not offer the same search to an ordinary timestamp index. Prefer direct bounds when they express the request naturally. A transformed value can instead have an expression index:

CREATE INDEX orders_utc_day
ON orders (((placed_at AT TIME ZONE 'UTC')::date));

The query must use an expression the planner recognises as matching this stored value. A bare placed_at::date depends on the session time zone, so it is neither the same UTC question nor a suitable immutable expression for this PostgreSQL index. An index expression must keep the same meaning for the same input.

The same test applies to casts, types, text comparison and operators. A cast on a parameter may leave the stored column's order usable; a transformation of the indexed column may require a different index. Some equivalent expressions can be simplified by a planner, so inspect the resulting search rather than declaring that every function or cast prevents indexing. PostgreSQL index methods and operators explains native operator support and the methods used when ordinary B-tree order is not the useful structure.

Selectivity and where the rows live

Selectivity is the fraction of rows a condition matches. A rare customer's full history and a common customer's full history are different searches, even though both use customer_id = .... In this generated fixture customer 1001 owns 84,000 orders; customer 1002 owns 36. The time-first index can meet the common customer frequently while scanning by date; finding the rare customer in the same order can take much more work.

Row placement changes the price of fetching those matches. Suppose the same twelve rows occupy four pages, three rows per page. One layout mixes customers across the pages; another groups the rows by customer. Widening the condition from one customer to two, then all three, increases the matching rows without increasing the table’s size.

The same matches can reach different pages
Figure 3. Two invented physical layouts of the same twelve selected rows. This small selection does not reproduce the full fixture's customer frequencies. The counters track row fetches and table pages; index work, caching and storage latency are outside the model.
Figure as text

With customers mixed, four, eight or twelve matching rows reach all four pages. Grouping the same rows by customer reduces those page counts to two, three or four. Repeated visits to a page are still work; the drawing does not count physical storage reads.

With mixed customers, four matches reach all four pages. Fetching eight or twelve rows revisits pages without finding a new page to skip. With rows grouped by customer, four matches reach two pages. The number of matching rows alone cannot describe either cost.

A bitmap route collects row locations before fetching the table in page order. That can avoid repeated or scattered fetches, but it gives up the index's ordering. A sequential scan reads the table once without collecting index locations first. Either can beat an ordinary index scan for a broad request. There is no universal percentage at which the choice changes: row width, physical placement, caches, storage, sorting and early stopping all matter.

Some engines can combine separate indexes: intersect the locations for customer and status, for example, or unite locations for an OR. That flexibility can serve varied searches, but collecting and combining locations costs work and can lose useful ordering. A composite key can go directly to a frequent conjunction. Query execution and performance explains how to compare estimated and measured work when choosing between these routes.

Covering indexes and index-only scans

The history key already stores customer, time and ID. Status is the only selected value it lacks. PostgreSQL can add it as leaf payload without making it part of the search order:

CREATE INDEX orders_history_cover
ON orders (customer_id, placed_at DESC, order_id DESC)
INCLUDE (status);

This is a covering index for this query: it holds every value the query needs to select, filter and order. Covering is relative to a query. Adding a returned column absent from this index can require the table again. Status payload can be returned or tested; it does not direct a search to the paid rows.

An index-only scan can obtain the result values from those entries. It must still establish that each row version is visible to the reader. PostgreSQL can avoid a heap fetch when its page visibility information confirms that; a recently changed page can require the heap even though the values are covered. Covering the values and proving visibility are separate requirements.

Fewer row fetches or fewer entries?
Figure 4. Customer 1001, since 1 October, paid only, LIMIT 1 on the selected rows. The visibility option represents whether the engine can confirm visibility without fetching that row; it does not simulate vacuum or transaction internals. Every setting returns order 100012.
Figure as text

The query wants the newest paid order for customer 1001. The full range contains two pending entries before one paid entry. Key only must fetch all three rows for status. Including status avoids those fetches only when visibility can also be confirmed without the row. A paid-only partial index contains just the one eligible entry; its visibility check may still require a table fetch.

Consider the newest paid order for customer 1001 since October, with LIMIT 1. In the selected rows, the first two entries are pending and the third is paid. Adding status leaves those same three candidates in the time range. It can save their row fetches, but the scan still passes two pending entries to reach the paid one. Making status a later search key can also reject entries inside the index; it does not automatically shorten the interval.

Wider entries occupy more space, leave fewer entries per leaf and add maintenance when their payload changes. A frequent history screen may earn that cost; an occasional query may not.

Partial indexes

A partial index stores entries only for rows satisfying its own predicate. A paid-only history index excludes pending rows before there is anything to traverse:

CREATE INDEX orders_paid_history
ON orders (customer_id, placed_at DESC, order_id DESC)
INCLUDE (status)
WHERE status = 'paid';

The full fixture has 20,158 paid orders, about 17% of its orders. The partial index therefore holds a smaller population than all-status history. It is not a replacement for that history: pending orders are absent. Nor is the fixture's pending population a small queue. The subset and its future distribution have to earn their own design.

The planner must establish that the query needs only rows present in the partial index. A query with a fixed status = 'paid' states that directly. A reusable plan with an unknown status = $2 cannot assume the parameter will always be paid; a custom plan with a known value can have different information. Predicate implication and recognisable expression forms limit what the planner can prove. Test the application's actual prepared-query behaviour.

Indexes for joins and foreign keys

The same leading-key reasoning applies when a row from another table supplies the search value. The shop's order_items primary key is (order_id, line_no). It groups one order's numbered lines. A nested-loop join can take order 103 and find its two lines through that leading order ID. The key does not give a similarly direct contiguous lookup for every line numbered 1 across all orders.

Looking up a customer's orders is useful beyond the history screen. A parent change that checks references may need those same rows. The unique index behind customers(customer_id) supports finding the referenced customer; it does not find the orders which refer back to that customer. A customer-leading history index can serve that reverse lookup as well as the screen.

Inspect what the engine already created. PostgreSQL creates indexes for primary-key and unique constraints but does not automatically create an index on every referencing foreign-key column. Other engines differ. An ordinary performance index also does not impose uniqueness unless declared unique: adding UNIQUE to a customer-and-time key would introduce a business rule refusing equal-time orders for that customer. Constraints and data integrity explains those rules; Query execution and performance compares joins which repeat lookups with methods which read their inputs together.

What each index adds to writes

Each index stores another version of selected facts. An insert must add entries to the indexes whose predicates it satisfies. Changing a key moves the entry to another ordered position. Changing payload replaces stored data even when no search bound changes. Crossing a partial-index predicate adds or removes membership.

Consider a separate update that changes order 100042 from pending to paid. A history index keyed by customer, time and ID keeps the same key values. An index that includes status must change that leaf payload. A paid-only index must add the order to its subset. These are alternative designs being compared, not a recommendation to keep all three.

Figure 5 · One status change reaches different index facts
Order 100042 · 25 October · customer 1001
pending → paid
  • History key
    (customer, time, ID)
    Key values stay the same. Whether new index entries are needed still depends on the engine's row-version update.
  • History key
    INCLUDE (status)
    The leaf payload changes from pending to paid. Keeping the key fixed does not remove this maintenance.
  • Paid-only history
    WHERE status = 'paid'
    The row enters the subset. A new entry must represent its paid membership.

A model of required data changes, not a measured count of dirty pages or log bytes. The baseline fixture remains unchanged.

These changes consume memory, storage and log work. When the destination leaf is full, a B-tree may split a page and update its parent; a split can propagate upwards. Key insertion order affects where that work lands. Sequential keys concentrate insertion at an edge, while dispersed keys can touch many leaves. Neither pattern removes contention or the need to measure under concurrent writes.

Update details differ. PostgreSQL can avoid new ordinary B-tree entries with a heap-only tuple, or HOT, update when no index-relevant column changes and the new row version fits on the same heap page. Index payload and partial-predicate columns count too. If that optimisation is unavailable, even an index whose key values stayed the same can receive a new entry. A clustered table has another coupling: changing its clustered key also changes the locator carried by secondary indexes.

Deletion and version cleanup add later work; freeing entries does not necessarily shrink files immediately. Larger or sparse indexes can occupy more of the cache and cost more to scan and back up. Fill factors, cleanup and rebuild procedures need engine-specific evidence. PostgreSQL schema changes under load covers native build and maintenance procedures.

Choose a set for the workload

One index per query quickly duplicates work. The history key's customer prefix can also serve an unbounded customer list and the referencing-side lookup. The order-line primary key already serves line lookups. A paid-only history index adds a different subset, while a broad customer-total report may prefer reading many rows together.

Each candidate needs a distinct saving across the shop's requests
RequestUseful routeQuestion before keeping it
Ten recent orders for one customerCustomer, time and ID; optional status payloadDoes early stopping keep the range small for common and rare customers?
Recent paid orders for one customerThe history key with checks, a status-leading variant, or paid-only historyHow many candidates are rejected, and what else needs all statuses?
Lines of one orderExisting (order_id, line_no) primary keyDoes another proposed index add a useful search this key lacks?
Broad paid-order totalsA narrow order range where useful, or scans feeding joins and totalsDoes the index save table work after accounting for all contributing lines?

A plain customer index beside the history key is a candidate for investigation, since both support customer equality. It can still be narrower and cheaper for a particular lookup. Different uniqueness, predicates, directions, payload and rare administrative jobs can give apparently similar indexes different purposes. Check dependencies and representative usage before choosing removal. Live schema changes and backfills handles the compatible rollout; an isolated query improvement does not establish that a live index can safely be dropped.

Check that the proposed work disappeared

Start with a prediction. The ordered history key should remove the customer-only path's large candidate fetch and sort. Status payload should reduce table fetches when visibility permits. A paid-only index should exclude pending entries from its traversal. These are stronger tests than “the plan used my index”.

Run the same query and parameters before and after each candidate on the same data and statistics state. Compare complete ordered results first. Then inspect the bounds, sort input, rejected candidates, row fetches and page counters. Conditions labelled as index conditions may include later-column checks, so their presence alone does not establish how much index traversal disappeared.

The accompanying experiment compares customer 1001 with customer 1002, lower bounds of 1 January and 1 October, and all-status with paid-only requests. It keeps only one candidate secondary order index at a time. Its observed plans and index sizes belong to that generated workload, not a universal index ranking.

On the owned Linux PostgreSQL 18.6 server, all seven variants returned the same ordered results for each of those eight parameter sets. The table below shows all-status history since 1 January. Both customers have at least ten orders, so both requests return ten. Counts are whole-query shared-buffer accesses, hits plus reads, rather than different pages or storage operations.

Observed PostgreSQL 18.6 plans · one candidate at a time · LIMIT 10
Candidate on ordersCustomer 1001Customer 1002
Primary key only765 accesses · scan, sort 84,000 rows765 accesses · scan, sort 36 rows
Customer only765 accesses · scan, sort 84,000 rows38 accesses · fetch 36, then sort
Time, customer and ID16 accesses · ordered index scan392 accesses · 127 index searches
Customer, time and ID13 accesses · ordered index scan13 accesses · ordered index scan
History key with status payload, after vacuum4 accesses · index-only scan4 accesses · index-only scan

The customer-only index was not chosen for the common customer’s large run. Time first looked competitive for that customer but made 127 searches for the rare one: this PostgreSQL version used repeated searches rather than one uninterrupted traversal. The customer-leading history key made one search in each case and removed the sort. Key order explains which searches are possible; the actual plan establishes which native route occurred.

Paid-only history since October gives a different comparison. For customer 1001, the covering scan rejected 82 pending candidates before returning ten paid orders. Before vacuum it reported 92 heap fetches and 95 shared-buffer accesses. After vacuum it still rejected 82, but reported zero heap fetches and four buffer accesses. The paid-only partial index reported no rejected status candidates, zero heap fetches and three accesses. Covering removed table work; the partial predicate removed unwanted membership.

The history key occupied 4.67 MiB, the covering version 5.70 MiB and the paid-only version 0.97 MiB in this run. That smaller partial index still could not answer all-status history. The one-day comparison also returned identical 329 order IDs: direct timestamp bounds and a matching UTC-date expression index used bitmap routes, while the transformed date without its expression index scanned all 120,003 orders.

Download the experiment entry point, its fixture and comparison SQL into one directory to reproduce the work in an explicitly chosen disposable PostgreSQL database. The recorded results and plans retain the parameters and counts. This run disabled parallel query and JIT compilation, used the default 4 MiB working-memory allowance and 128 MiB shared-buffer pool, and controlled automatic vacuum to expose the visibility change. It establishes access work and result equivalence; it does not measure production latency or competing-write cost.

Entry counts in the small examples describe the specified traversals. Native plans need their own interpretation. Emitted rows do not count every entry passed over. Repeated buffer accesses are not counts of different pages. A buffer read need not reach the storage device if the operating system caches it. Reading and repairing PostgreSQL plans develops those native fields.

Finally test the request mix and competing writes. Measure whether saved reads earn the extra space, cache demand and maintenance over time. A history request that saves hundreds of row fetches is a useful result. Whether a second covering or partial index earns its ongoing cost depends on how often those requests run and what shares the table.

Sources and further reading

The small examples use selected values from the shared fixture, with invented table pages and row locators. The measured comparison ran on an owned disposable Linux PostgreSQL 18.6 server; no InnoDB or production workload was measured. Technical claims were checked against the following primary documentation on 25 October 2026.