BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
SQL and Relational Database Engineering

Advanced · Lesson 8 of 12

Software Architecture

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.

A stopwatch, printouts and two route markers on a dispatch analyst’s desk.

The dispatch supervisor requests the day's handling fees for depot 7 on route 1007. A PostgreSQL plan says the report returns one row, exactly as predicted. A few lines lower, the scan expects roughly ten tickets and finds a thousand. Someone points at the words “sequential scan” and asks for faster storage. Which observation explains the delay? Before approving a hardware change, you can run two experiments that separate an error in the planner's arithmetic from time actually spent fetching data.

Take a copy of the report into a disposable database. We will construct a shift containing exactly one hundred thousand tickets. The important feature is how dispatch assigns routes. Every ticket from a given depot goes to the same route during this shift. Someone who knows that rule can predict the result with a pencil. Someone who knows only the separate frequencies of routes and depots is likely to get it spectacularly wrong.

اقرأ الدرس بالعربية

Establish a result you can verify

Run the setup once in an empty practice database. Use an ordinary table so the plan can report shared buffer activity. The primary key supports ticket lookups, but we deliberately start without an index on either report filter. Store fees as whole fils. This report is a sum over a single shift, with no currency conversion, cancellations or outstanding balances to complicate the result.

CREATE TABLE sq08_dispatch (
  ticket integer PRIMARY KEY,
  depot integer NOT NULL,
  route integer NOT NULL,
  fee_fils integer NOT NULL
);
INSERT INTO sq08_dispatch
SELECT i, i % 100, 1000 + i % 100, 250
FROM generate_series(0, 99999) AS g(i);
ANALYZE sq08_dispatch;

Depot numbers cycle from zero to ninety-nine. Each depot appears on exactly one thousand tickets. Its route number is always one thousand plus its depot number. Ticket 7 qualifies, ticket 107 qualifies, and the last qualifying ticket is 99907. At 250 fils per ticket the report must return one thousand tickets and 250,000 fils, or AED 2,500. Record those figures before reading the plan. A fast change that alters the invoice amount is a failed change even when the new estimates are excellent.

SELECT count(*) AS tickets, sum(fee_fils) AS total_fils
FROM sq08_dispatch WHERE depot = 7 AND route = 1007;

EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)
SELECT count(*), sum(fee_fils)
FROM sq08_dispatch WHERE depot = 7 AND route = 1007;

The first query prints the business result. The second executes the same calculation and describes the execution. Read the tree starting where data enters. In a simple serial plan the scan applies the two predicates and passes matching tickets to an aggregate. The aggregate emits one summary row. Its output cardinality would still be one if no ticket qualified: count would be zero and sum would be null. Comparing only estimated and actual rows at the top would miss the very error we introduced.

Find the first mistaken prediction

On the scan line, the rows field inside the cost section is the planner's estimate of the rows the node will emit per execution. The actual rows field reports what it emitted when measured. Neither number counts every ticket examined by the scan. A serial sequential scan here inspects a hundred thousand rows, keeps a thousand and rejects ninety-nine thousand. The filter line explains what was tested, and the rows removed by filter account for the rejected rows. The PostgreSQL guide shows how these quantities fit together in Using EXPLAIN.

Where does the estimate of ten come from? One ticket in a hundred belongs to depot 7. One in a hundred travels on route 1007. Multiplying these proportions as though the choices were independent gives one in ten thousand. Applied to the entire shift that predicts ten tickets. The actual result is one hundred times larger. Compare this model with the scan estimate you obtain; samples, configuration and PostgreSQL version can move the estimate away from exactly ten. The thousand qualifying rows follow directly from the data generator and do not depend on the planner.

A useful incident note names the node, both numbers and the direction of the error. “The filter feeding the aggregate underestimated matching tickets by about two orders of magnitude” gives a colleague a hypothesis to test. “The query returned more than expected” is ambiguous because the report returned exactly one row. If a node repeats, compare estimated and actual rows per execution first. In text plans actual rows and node times are averages across loops. An inner lookup returning three rows on each of a thousand executions delivers about three thousand rows in total. Multiplying only one side before comparing it with the estimate manufactures a new discrepancy.

Change the planner's information first

CREATE STATISTICS sq08_depot_route (dependencies)
ON depot, route FROM sq08_dispatch;
ANALYZE sq08_dispatch;

Run precisely the same report and plan again. The statistics object asks PostgreSQL to learn the relationship between the columns during analysis. Creating its definition alone does not collect observations. Expect the estimate for this compatible pair of equality conditions to approach the thousand actual tickets. The invoice must stay at AED 2,500. Save both plans with the query parameters so someone else can check these claims. PostgreSQL's multivariate statistics examples demonstrate this kind of dependency and its limits.

Now look at the physical work. With no suitable secondary index and every ticket potentially contributing to the sum, the same sequential scan can survive the correction. It may visit much the same set of table blocks as before. That is a successful experiment: you have repaired a particular prediction and discovered that the chosen read path need not change. In a bigger report the improved estimate might affect join order or the choice between repeated lookups and a hash join. This simple aggregate isolates the estimation question without promising a speedup.

Try depot 7 with route 1008 on paper. It produces zero rows at the scan, although both individual values occur frequently. Dependency statistics need not tell the optimizer that this particular pairing is impossible. If incompatible pairs dominate the production workload, examine a multicolumn most-common-values statistic and actual predicates before choosing a remedy. One successful estimate on the common compatible pair is not a guarantee about every pair, every parameterized plan or a join between different tables.

Measure page access and elapsed time separately

SHOW track_io_timing;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON)
SELECT count(*), sum(fee_fils)
FROM sq08_dispatch WHERE depot = 7 AND route = 1007;

The JSON format makes it easier to keep two captures and compare the same node across runs. The statement still executes the report. Turning per-node timing off reduces clock-reading overhead while retaining row counts, buffer counters and overall execution time. Keep planning time separate from execution time. Planner cost numbers also use relative cost units; subtracting a cost estimate from an execution time in milliseconds produces no useful measure. The EXPLAIN command reference documents the instrumentation switches and the meanings of the buffer fields.

At the scan, shared hits mean requested blocks were already available in PostgreSQL's buffer cache. Shared reads mean blocks had to be brought into it. The operating system may have served some reads from its own cache. A count of reads alone cannot prove that the storage device was slow. Parent buffer figures include work performed by children, so adding the scan and aggregate counters double-counts the same work. Buffer counts are accesses, and repeated visits to a block can count more than once.

For an interpretation drill, suppose two serial captures of this same scan show about 1,000 estimated and 1,000 actual rows. In the first, shared read is 540, measured read time is 42 milliseconds and total execution time is 55 milliseconds. In the second, those accesses are hits and execution takes 10 milliseconds. These are illustrative captures, not timings from the generated table. The rows agree in both. The timing and change in cache behavior support investigating reads in the first capture. Conversely, ten estimated versus a thousand actual on a run consisting entirely of shared hits establishes a prediction error without evidence of costly physical reads on that run.

Use the server's actual timing configuration when interpreting missing fields. If I/O timing is disabled, the absence of a read-time figure means you did not measure that duration. If enabled, compare like-for-like captures under similar load and note whether the relation had just been scanned. On parallel plans, times accumulated across workers do not translate directly into wall-clock percentages. PostgreSQL describes the timing setting and its overhead in run-time statistics configuration.

Test a different access path

CREATE INDEX sq08_lookup ON sq08_dispatch (depot, route);
ANALYZE sq08_dispatch;

Repeat the report, retain the same parameters and check the fee total. The index offers a route to qualifying ticket locations. PostgreSQL might choose a bitmap heap scan, an ordinary index scan or retain a sequential scan. Our fixture scatters the matching rows through the heap, one every hundred tickets. Finding their locations cheaply may still require touching many heap pages to read the fee. Look at the heap blocks and execution time before claiming that using the index solved the complaint. An index also adds storage and maintenance on writes, which the dispatch intake service must pay for every shift.

When reporting the experiment, keep three observations side by side: the scan's estimate versus actual, the pages and time required for the chosen path, and the unchanged business result. If only the estimate improved, say so. If the measured report improved only after the table was read once, record that condition. The supervisor can then decide whether the relevant experience is a repeatedly refreshed dashboard or the first report after a long quiet interval.

Exercise: diagnose the remaining complaint

A colleague repeats the original report after collecting dependency statistics. The scan now estimates 980 tickets and emits 1,000 once. The report still takes 80 milliseconds, and the plan reports shared reads but no I/O times. Write two sentences for the incident and choose one next measurement.

Answer. The estimate is about two percent low and the report still totals AED 2,500. The reads justify investigating page access, but there is no measured duration that attributes the 80 milliseconds to storage. Capture the same query with I/O timing available in a controlled environment, record scan buffers and total execution time, and compare a repeat under the same load. A defensible diagnosis identifies which evidence changed and whether the cashier still gets the same invoice.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Design an Index for a Real Query

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.

Software Architecture9 min read

Commit a Transfer Atomically

A mistyped till code interrupts a transfer of AED 75. Post both ledger entries in PostgreSQL and check exactly what survives a rollback.