Read a PostgreSQL Query Plan
A fee report returns one summary row, but its scan finds a thousand tickets where the planner expects roughly ten. Diagnose the estimate and test the I/O hypothesis.
Advanced · Lesson 7 of 12
Software Architecture
A dispatch clerk needs twenty ready tickets from 100,000 records. Choose a composite index for her queue and measure what the faster lookup costs on inserts.

A dispatch clerk opens the collection queue for branch seven. She wants twenty tickets ready for pickup, newest batch first. The system has a hundred thousand tickets, but only four hundred belong on her list. A colleague proposes indexing the status column. Another proposes indexing the batch number because the screen always sorts by it. Both columns appear in the SQL. Which index lets the database stop working as soon as the clerk has her twenty tickets, and how much extra work will it create for the service accepting deliveries?
We will build two copies of the same dispatch table, give one a composite B-tree index, and compare both the read path and the cost of inserting a batch. The result needs two kinds of evidence. The same twenty ticket identifiers must come back in the same order. The measured improvement also needs to justify maintaining another data structure on every insert. An index can satisfy the first test perfectly and still be a poor investment for a rarely opened screen.
A row represents one ticket, and its identifier is unique. A batch is a collection of tickets admitted together. Larger batch numbers are newer. Within one batch the clerk wants the larger ticket identifier first. This last rule determines which tickets make the cut when a batch extends across a page boundary. Without it, two valid query plans might display different tickets at the end of a page, making a performance comparison look like a correctness regression.
Use a disposable PostgreSQL database and one session. The two benchmark tables are ordinary logged tables so their inserts can generate write-ahead log records. The temporary view produces repeatable input. The baseline already has the primary-key index, as a real ticket table usually would. The only intended structural difference between the two destinations is the queue index. Start each fresh trial with empty tables created by this setup.
CREATE TABLE sq07_plain (
id integer PRIMARY KEY, branch integer NOT NULL,
state text NOT NULL, batch integer NOT NULL, label text NOT NULL
);
CREATE TABLE sq07_indexed (LIKE sq07_plain INCLUDING ALL);
CREATE TEMP VIEW sq07_input AS
SELECT i AS id, i % 50 AS branch,
CASE WHEN (i / 50) % 5 = 0 THEN 'ready' ELSE 'sent' END AS state,
i / 1000 AS batch, 'P' || i::text AS label
FROM generate_series(0,109999) AS g(i);
INSERT INTO sq07_plain SELECT * FROM sq07_input WHERE id < 100000;
INSERT INTO sq07_indexed SELECT * FROM sq07_input WHERE id < 100000;
CREATE INDEX sq07_queue ON sq07_indexed
(branch, state, batch DESC, id DESC);
ANALYZE sq07_plain;
ANALYZE sq07_indexed;
The first hundred thousand integers make two thousand tickets per branch. Within a branch every fifth ticket is ready, so branch seven contributes four hundred ready tickets. Each thousand consecutive identifiers belongs to a single batch. You can predict the result without trusting an optimizer. The matching identifiers begin at 7 and advance by 250. The last one below 100000 is 99757. Since batches increase with identifiers in this sample, the twentieth ticket on the descending list is 95007. These are checks on the fixture; real ticket numbers need not track time.
SELECT id, batch, label
FROM sq07_indexed
WHERE branch = 7 AND state = 'ready'
ORDER BY batch DESC, id DESC
LIMIT 20;
Picture the keys in sorted order. With branch first, the records for branch seven are adjacent. Within that branch, state separates ready records from sent records. Once the database has located that combination, batch and identifier place the eligible tickets in the exact order the clerk needs. The engine can walk forward through that part of the tree and stop after twenty visible matching records. The label still comes from the table. There is no need to duplicate every label inside the index just to demonstrate the early stop.
Why put branch before state if the query tests both for equality? For this exact combination, reversing those first two columns can also locate one contiguous range. Branch first is a design choice for related branch-scoped lookups. It need not be the best choice for a supervisor who routinely works across all branches. Nor does the branch prefix by itself deliver a time-ordered list across every state, because state still separates the batches within that branch. Evaluate plausible neighboring queries instead of reciting a rule about putting the most selective column first. The PostgreSQL guide to multicolumn indexes describes how leading equality conditions constrain a B-tree scan.
A batch-first index makes a different promise. It can start at the newest end, but may pass many tickets for other branches or states before collecting twenty matches. A status-only index can find ready tickets across the company, yet leaves work to select the branch and obtain the requested order. Combining separate indexes with a bitmap can help filter rows but does not preserve the queue's requested sequence. For a small limit, avoiding a separate sort can be more valuable than finding every eligible ticket quickly. PostgreSQL explains that distinction in Indexes and ORDER BY.
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)
SELECT id, batch, label FROM sq07_plain
WHERE branch = 7 AND state = 'ready'
ORDER BY batch DESC, id DESC LIMIT 20;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)
SELECT id, batch, label FROM sq07_indexed
WHERE branch = 7 AND state = 'ready'
ORDER BY batch DESC, id DESC LIMIT 20;
Run each query once to warm the working set and then alternate the two versions several times. Record the actual rows, buffer activity and total execution time. In the baseline look for how the system finds qualifying records and where it establishes the order. Even a bounded sort that keeps only the best twenty candidates must consider all matching input offered to it. The relevant number is the rows flowing into that sort. Seeing twenty at the top of the plan alone tells you little about the work underneath.
In the candidate plan, look for a Limit fed by an ordered index scan, equality conditions on branch and state, and no separate Sort step. Read the index name. An index scan using the primary key and applying the business predicates as a filter could still visit many unrelated tickets. Check rows removed by filtering and buffers alongside elapsed time. If the planner prefers a sequential scan, first check whether statistics are current, the table size resembles the intended workload, and the literal values match your test. A forced index plan demonstrates that a route exists, not that the optimizer should choose it in service.
As a cross-check, I ran the same key arrangement and integer fixture with SQLite 3.53.1. Its baseline plan scanned the table and used a temporary B-tree for ordering. Its indexed plan searched the composite index by branch and state. Both returned 99757 first and 95007 twentieth. These observations illustrate the access pattern on a second engine. Use the PostgreSQL commands above to obtain PostgreSQL plan nodes and buffer counts on the deployment you are evaluating.
CREATE TEMP TABLE sq07_new AS
SELECT * FROM sq07_input WHERE id >= 100000 ORDER BY id;
EXPLAIN (ANALYZE, BUFFERS, WAL, TIMING OFF)
INSERT INTO sq07_plain SELECT * FROM sq07_new ORDER BY id;
EXPLAIN (ANALYZE, BUFFERS, WAL, TIMING OFF)
INSERT INTO sq07_indexed SELECT * FROM sq07_new ORDER BY id;
SELECT pg_size_pretty(pg_relation_size('sq07_queue')) AS index_size;
EXPLAIN ANALYZE executes each insert. Run the pair once per fresh setup. Each destination receives the same ten thousand previously unused identifiers, including the same labels and the same order of insertion. Building the temporary batch first keeps input generation outside both measured inserts. The primary key is maintained in both cases. The candidate must additionally locate an insertion point for each queue key and update its index pages. Record total execution time, buffers dirtied and WAL bytes. Use the index size as a separate storage measure. The size in bytes cannot tell you how long a write waited. The EXPLAIN command reference defines the counters and what the command actually executes.
For a concrete write measurement, the SQLite cross-check used seven fresh pairs of on-disk databases. Each started with the same hundred thousand tickets. I timed one transaction of ten thousand parameterized inserts including commit, alternating which configuration ran first across trials. Median batch times were 5.82 milliseconds with the baseline and 13.73 with the queue index. In that environment maintaining the index added about 7.91 milliseconds per batch. The numbers belong to that fixture, engine, storage and transaction size. They are not latency estimates for ten thousand separate network requests. In particular, the PostgreSQL plan's execution time and a client's wall-clock time through commit measure different boundaries.
Repeat the PostgreSQL comparison on representative storage, alternate the order of the tables across fresh trials, and report a median along with the variation. Checkpoint timing can alter full-page images in the write-ahead log. Cache warmth and background activity can change the elapsed time without changing the SQL at all. Compare like with like. If your real writes move tickets from ready to collected, measure that update too. State is now an indexed column, so an insert-only benchmark misses part of the maintenance cost. PostgreSQL discusses ongoing maintenance in its introduction to indexes.
Separate the frequent interactive read from the occasional export. A request for all four hundred ready tickets may have a different plan and a different bottleneck. Run the actual page size and record how often that page is requested relative to inserts and state transitions. Suppose a service budget allows eight milliseconds of additional median time per ten-thousand-ticket batch. Our illustrative write delta barely fits that budget and leaves little margin for variation. That alone says nothing about whether the queue is fast enough. A deployment decision also needs measured read latency at the required load and confirmation that workers can sustain the incoming write rate.
A partial index is another candidate if the only urgent screen always asks for ready tickets. On that hypothesis you could index branch, descending batch and descending identifier with a predicate restricting entries to ready tickets. In the initial fixture only twenty thousand of the hundred thousand tickets would have entries. A sent ticket inserted directly would skip that index, while a ready ticket leaving the queue would still incur maintenance. Test the exact application query, including how its status parameter is bound. The planner must be able to establish that the query's condition implies the index predicate. A partial index also cannot serve the supervisor who asks for the newest sent tickets.
Tomorrow the clerk wants the latest twenty tickets for branch seven regardless of state. Keep the batch and identifier ordering. Predict whether the existing index can return the whole branch in that order simply by scanning its entries forward. Sketch an alternative, then compare plans and output identifiers on the original hundred-thousand-row fixture before the write test.
Answer. Within branch seven the existing index keeps the states in separate runs. Reading them consecutively can put an older ready ticket ahead of a newer sent ticket. A candidate index on branch, descending batch and descending identifier puts the whole branch in the requested order. The expected first ticket is 99957 and the twentieth is 99007. Confirm all twenty identifiers match the baseline, inspect whether the sort disappears, and repeat the write comparison with exactly the indexes you intend to retain. Keeping both indexes changes the bill for every delivery, even on days when nobody opens the second screen.
YOUR TAKE
Choose one reaction for this article.
A cookie helps limit repeat responses. Your feedback is private.