Relational databases
Reading and repairing PostgreSQL plans
A PostgreSQL plan contains several different kinds of number. rows=3 can describe three lines returned once or an average of three lines returned thousands of times. shared hit=36822 counts buffer accesses across those repetitions. It does not mean that 36,822 different pages were read from storage. Reading the units correctly changes which repair is worth trying.
The shop's report adds agreed order-line values for October's paid orders, grouped by customer. On the small shop rows, Tariq contributes 40.00 and Mina 39.50; pending order 103 contributes nothing. We will use the same generated history as Query execution and performance: 120,003 orders and 360,005 lines, with deliberately uneven customer frequencies and related date and status values. These are reporting data, not a reconstruction of stock or payments.
The measured plans below come from an isolated Linux PostgreSQL 18.6 server. They establish what that server did with this fixture. The drawings reorganise its counters to make them readable; where a drawing uses invented numbers, it says so. Inside PostgreSQL supplies the physical setting of backends, heap pages and shared buffers.
EXPLAIN and EXPLAIN ANALYZE
EXPLAIN asks PostgreSQL how it intends to obtain a result. EXPLAIN ANALYZE also executes the statement and records its work. It can therefore perform a write, call a function or wait for a lock. Choose the statement and target as carefully as for ordinary execution. Rolling back a test can undo transactional changes; it does not undo every possible external effect of a function.
Here is the per-order version of the report. The lateral subquery uses the current order's ID to calculate one order total, and the outer aggregate adds those totals by customer. The HAVING condition suppresses an order with no lines, preserving the original inner-join report's contributing-customer rule.
SELECT o.customer_id, SUM(v.order_value) AS line_value
FROM orders AS o
CROSS JOIN LATERAL (
SELECT SUM(i.quantity * i.unit_price) AS order_value
FROM order_items AS i
WHERE i.order_id = o.order_id
HAVING COUNT(*) > 0
) AS v
WHERE o.status = 'paid'
AND o.placed_at >= timestamptz '2026-10-01 00:00+00'
AND o.placed_at < timestamptz '2026-11-01 00:00+00'
GROUP BY o.customer_id
ORDER BY line_value DESC, o.customer_id;For a first measurement, prefix that statement with:
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SETTINGS)
-- followed by the SELECT aboveTIMING OFF keeps actual rows, loops and whole-statement execution time while avoiding the repeated clock reads used for individual node timings. Enable node timing when the location of elapsed time is the question. SETTINGS reports relevant planning settings that differ from built-in defaults; retain other experiment settings yourself. FORMAT JSON is useful when comparing plans programmatically.
What the measurement includes
Planning time and execution time are separate fields. Neither is the application's complete request time: connection-pool waiting, the client round trip, result transfer and client processing have their own boundaries. By default, EXPLAIN discards the query's output without converting it for transmission. PostgreSQL 18's SERIALIZE TEXT or SERIALIZE BINARY can include output-conversion work, but still does not send the result over the network.
Keep the actual parameters, SQL, server version, indexes, statistics state and settings with the plan. A different customer, a newly built index or a warmer cache can explain a change before any proposed repair does. PostgreSQL 18 includes buffers automatically with ANALYZE; spelling out BUFFERS makes the intention explicit and works on older versions too.
Rows, loops and cardinality estimates
The report's order scan estimates 1,752 eligible orders and emits 9,176. The line lookup then runs once per eligible order. Its per-loop count and the whole-report total therefore describe different amounts of work.
actual rows=9176 loops=1actual rows=3 loops=9176actual rows=1 loops=917627,525 lines across 9,176 lookups. The displayed three rows per loop is rounded; it is not the whole result.
A row-flow drawing extracted from the measured October per-order report on PostgreSQL 18.6. It turns the native tree upright; arrows carry rows, rather than elapsed time. Costs and intermediate sort details are omitted.
Figure as text
- Start at the orders scan. Its rows are the orders emitted after the date and status tests, not all orders examined.
- The outer scan emits 9,176 eligible orders. The inner aggregate therefore runs 9,176 times, once for each order.
- Inside each aggregate, the index scan emits about 3 lines per loop. Across 9,176 loops it supplies 27,525 lines; the displayed average is rounded.
- The inner aggregate supplies one order total per loop. Grouping adds these by customer, leaving 991 customer totals.
- The final sort orders those customer totals. The repeated line lookup, not the small final answer, accounts for most buffer accesses.
The native line-lookup excerpt reads:
Index Scan using order_items_pkey on order_items i
(cost=0.42..11.97 rows=3 width=9)
(actual rows=3.00 loops=9176)
Index Cond: (order_id = o.order_id)
Index Searches: 9176
Buffers: shared hit=36822The estimated rows and actual rows describe rows emitted by one execution of this node. The actual value is an average over its loops. Multiplying 3 by 9,176 gives approximately 27,528 line rows, not three. The exact matched total is 27,525: the core orders have two lines and one line, whereas each generated order has three. Rounding the average hides that difference.
Index Searches is already a total across node executions. Here it agrees with the loop count. Other index scans can start several searches within one execution, so neither one search per loop nor one search per returned row is a general rule.
Rows returned and rows rejected
The order scan also reports Rows Removed by Filter: 110827. Added to its 9,176 emitted rows, that accounts for all 120,003 orders examined in this complete scan. An inner index lookup can instead exclude keys without fetching their heap rows. Absence from the result does not imply a rejected heap row.
A filter on a scan rejects candidate rows. A join filter rejects candidate pairs, which can be far more numerous. Rows Removed by Index Recheck counts candidates that failed a required exact check after an index supplied them. These rejection fields are per-loop averages when the node repeats, and their displayed rounding can hide small totals. Read each at the operation that performed the test.
Before calling a row estimate wrong, check whether the node was fully consumed. LIMIT can stop a scan after ten rows even when its estimate correctly describes thousands available. A branch labelled never executed supplied no measurement of its possible output. Zero actual rows can also mean no match on the particular loop, rather than no search work.
Repeated inner work
The inner aggregate's one emitted row is one order total. It runs 9,176 times, so the small number hides repetition rather than a small workload. Look at the child: it, too, has 9,176 loops. That establishes the repeated line searches.
A different plan might retain an inner result with Materialize, or cache parameter-key results with Memoize. Then repeated requests to that node need not repeat its child. For Memoize, inspect hits, misses and evictions alongside the child's loops. Follow the actual tree: multiplying every descendant by the outer row count would invent work that caching avoided.
Buffers and execution time
The line scan's 36,822 buffer hits are accumulated across all 9,176 executions. Do not multiply them by loops again. They are also included in the inner aggregate and every ancestor containing that work. Adding the parent’s count to its child’s would count some of those same accesses twice.
9,176 searches across all loops
765 + 36,822 = 37,587 accesses
The aggregate's copy is not another 36,822.
Measured execution counters from Figure 1. Nesting means “includes”, not a cache layout. Planning has separate buffer counters. All execution accesses were shared hits in this run; none was a shared read.
The statement made 37,587 accesses to cached blocks. It did not need 37,587 different blocks. Every descent can revisit the same upper index pages, and many line rows can share a heap page. The EXPLAIN buffer definitions distinguish three storage classes:
| Class | What it holds | Useful distinction |
|---|---|---|
| Shared | Ordinary table and index blocks | A hit found a block in shared buffers; a read obtained it from outside that cache. |
| Local | Temporary table and index blocks | These belong to the backend's local buffers, rather than shared buffers. |
| Temp | Short-lived working data | Sorts, hashes and similar operations can read and write temporary files. |
A shared read can be served by the operating system's cache; it does not prove a physical drive read. dirtied counts blocks this query changed from clean to dirty. written counts previously dirty blocks this backend evicted and wrote while executing; a read-only query can incur such a write. It does not count every write that background processes perform on its behalf.
With track_io_timing enabled, I/O timings help establish how much time those operations spent waiting. A block count alone does not supply that duration, and a measured read duration alone does not identify the storage layer that served it.
Costs and elapsed time
In cost=0.42..11.97, the first value is estimated startup cost, before rows can be emitted; the second estimates the full run. These are planner units, not milliseconds. A parent that needs only a prefix can favour low startup cost. An estimate for completing a scan still describes its full possible output even when a parent stops it early.
With node timing enabled, actual time=a..b gives elapsed milliseconds to first output and completion, averaged per loop. Multiply by loops to approximate that node's accumulated time. The time includes work in its children, so summing all node times counts some work twice. It is elapsed time while executing the node, not a measurement of processor time alone.
Parallel executions overlap as well. Their accumulated process time can exceed the statement's elapsed time without contradiction. Use the whole-statement Execution Time for that profiled execution's server duration, and ordinary request measurements for the boundary the user experiences.
Repairing cardinality estimates
The first consequential estimate error in our report is already at the orders scan: 1,752 estimated against 9,176 actual. That sends over five times as many orders into repeated lookups as predicted. Before changing the join, ask why the input estimate is wrong.
The standalone ANALYZE orders command collects planner statistics; it does not profile our SELECT. If a large load or change has made statistics stale, a targeted collection is a sensible experiment. Here the fixture was freshly analysed, and paid status is deliberately related to the date. More precise individual distributions need not describe their combination.
Three observations on the same order rows separate individual-column precision from joint information. The first uses ordinary column statistics. The next raises the date and status targets to 1,000 and collects again, but still estimates only 1,713 orders. The last also collects a multivariate most-common-values list and estimates the observed 9,176. Higher individual precision did not capture the joint date/status distribution.
Full bar = the 9,176 actual paid October orders. Every case scans the same 765 heap blocks and rejects 110,827 orders.
Observed PostgreSQL 18.6 estimates for the date/status filter. The latter two measurements select order IDs directly to isolate the scan. This fixture has only hundreds of date/status combinations; the large MCV target can describe them all. Exact agreement is not a general promise.
Column statistics and skew
pg_stats connects an estimate to its evidence. Common values and their frequencies describe concentrated populations; histogram bounds describe the remaining distribution. n_distinct estimates distinct values: a positive value is a count, and a negative value gives a fraction of the table's row count.
SELECT attname, n_distinct, most_common_vals,
most_common_freqs, histogram_bounds
FROM pg_stats
WHERE schemaname = 'your_schema'
AND tablename = 'orders'
AND attname IN ('customer_id', 'placed_at', 'status');Customer 1001 appears in our initial common-value list with frequency about 0.701. The fixture actually assigns that customer 84,000 orders, while customer 1002 has 36. A literal equality for 1001 gives the planner information an average customer cannot. If a consequential skew is poorly represented, a higher target on that column can help, at a cost in collection, storage and planning work. Collect again and inspect the resulting estimate; changing a target alone collects nothing.
Extended statistics and their limits
For our paired date/status population, the experiment is:
ALTER TABLE orders ALTER COLUMN placed_at SET STATISTICS 1000;
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;
ANALYZE orders;
CREATE STATISTICS orders_date_status (mcv)
ON placed_at, status FROM orders;
ALTER STATISTICS orders_date_status SET STATISTICS 1000;
ANALYZE orders;The multivariate list records frequently occurring combinations. It allows this estimate to reflect that paid orders are much more common in October than elsewhere. The scan estimate becomes accurate on this fixture, whose hundreds of date/status combinations fit the collected list. That exact agreement is not a general promise. The scan still examines the whole table. The statistics did not add an access path or remove the rows required by the report.
Choose the statistics kind for the estimation question. dependencies can describe redundant equality conditions on related columns; PostgreSQL does not apply that correction to our timestamp range. ndistinct helps estimate the number of groups across several columns. mcv describes particular combinations, but a small list cannot represent every combination in a high-cardinality history. Extended statistics also do not currently correct join selectivity estimates across tables. A statistics object is a testable hypothesis about one error, not a universal estimate repair.
Testing an access path
The customer-history request has a different opportunity. It asks for ten recent orders, not all customer totals. If an index supplies the required order, the executor can stop as soon as it has ten matches.
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;
CREATE INDEX orders_history
ON orders (customer_id, placed_at DESC, order_id DESC);First there was only an additional index on customer_id. PostgreSQL chose a sequential scan for this common customer. After the composite index was built, the planner chose an ordered index scan instead. Neither route was forced.
21,042 qualify
Entries arrive newest first
Observed PostgreSQL 18.6 routes. The first top-N sort holds 26 kB but still considers every qualifying input. The second plan's index scan estimates 21,175 available rows; emitting ten under Limit is deliberate early stopping, not an estimate error.
The prediction held: the sort disappeared and the scan supplied only ten rows. That first measured use of the newly built index included three shared reads. Comparing work is stronger than calling the later, warmer run fast merely because its elapsed time fell.
Conditions, searches and heap fetches
Index Cond means a condition is checked through the index. Leading equalities and the following range can bound a B-tree scan; a later key condition may only reject entries within the range already scanned. Consequently the label alone does not prove a short search. Compare output, searches and buffers.
Filter can expose later rejection. In a paid-only history request using this index, status is absent from the key, so fetched rows may still be rejected for being pending. A bitmap plan's Recheck Cond describes an exact condition the heap scan can need to verify, especially with lossy bitmap pages. Its presence alone does not establish that any candidate failed; inspect Rows Removed by Index Recheck and exact/lossy heap-block counts.
An Index Only Scan has the values needed by the query in its index, but can still visit the heap for visibility. Heap Fetches counts those fetches across its executions; it is not a count of distinct heap pages. All-visible heap pages let it skip those visits. Our observed history route is an ordinary index scan: the index does not include status. PostgreSQL index methods and operators develops the methods, operator classes and recheck semantics.
Comparing another route
The report's repeated aggregate suggests a SQL experiment instead. Express the direct join and add each line's exact numeric value within its customer. On this fixture, a bidirectional EXCEPT ALL comparison found no differing customer totals. The HAVING guard in the per-order form matters for an eligible order without lines; preserve that rule when checking other data.
SELECT o.customer_id,
SUM(i.quantity * i.unit_price) AS line_value
FROM orders AS o
JOIN order_items AS i USING (order_id)
WHERE o.status = 'paid'
AND o.placed_at >= timestamptz '2026-10-01 00:00+00'
AND o.placed_at < timestamptz '2026-11-01 00:00+00'
GROUP BY o.customer_id
ORDER BY line_value DESC, o.customer_id;With parallelism disabled for this bounded comparison, the direct form used a hash join and scanned all 360,005 lines. Its repeated inner aggregate disappeared and shared hits fell from 37,587 to 3,059. Yet its single profiled execution took 23.623 ms against 18.299 ms for the per-order form. Fewer buffer accesses did not establish a faster request. The route traded many small lookups for a larger scan; ordinary repeated executions are needed before accepting it.
Planner switches can help ask whether another route removes the suspected work. For example, a transaction-local enable_nestloop = off discourages nested loops, but cannot eliminate them where no other method is legal. Such a diagnostic changes the planning problem. Restore ordinary settings and test the intended SQL, statistics or index change there. Keep the index's space and write costs in the decision too.
Sorts, hashes and temporary files
A small final answer can conceal a large working set. Sort Method: external merge establishes disk sort work; an in-memory quicksort or top-N heapsort describes another route. A hash with Batches greater than one signals work divided into batches, with temporary file I/O. Inspect temporary blocks alongside the method, input rows and row width.
A separate native experiment sorted all 120,003 orders by status, time and ID, with parallelism disabled. At work_mem = 64kB, it used external merge sorting and reported 3,984 kB of disk space. At 32 MB it used quicksort with 7,760 kB of memory and no reported temporary blocks. This was a whole-table sort, not the report’s small final sort.
1,482 temp blocks read
1,598 temp blocks written
No temporary blocks reported
Observed PostgreSQL 18.6 sort runs with parallelism disabled. Both read the same 765 cached heap blocks. Disk footprint and accumulated block I/O are different quantities; neither directly tells you the memory needed for an in-memory sort.
First ask whether the query needs all those rows and columns at the sort. Then test a local allowance if a spill remains worth removing. work_mem is a base allowance per working operation, not one budget shared by a whole statement. Hash operations can use work_mem × hash_mem_multiplier. Several operations, parallel processes and simultaneous requests can multiply the memory demand.
Use SET LOCAL work_mem = '32MB' inside an explicit transaction for a bounded test. The observed in-memory sort establishes that this particular spill disappeared. It does not establish a safe global setting for the shop. Measure competing reports and writes before extending the change.
Parallel plans
Gather collects rows from parallel work; Gather Merge combines streams that already have useful sort order. In a two-stage aggregate, workers produce partial states and the leader finalises them. A partial customer count is not yet the final answer if several processes saw that customer.
A separate diagnostic query counts all orders by customer. Parallel setup and transfer costs were deliberately set to zero and the scan threshold lowered to obtain a small diagnostic parallel example. It demonstrates counters, rather than a recommended configuration or a speed improvement.
120,003 rows across leader + 2 workers
3,000 partial customer counts in total
Worker 0 scanned 31,871 rows; worker 1 scanned 31,612. The leader supplied the remaining 56,520. Those are overlapping participants in one execution, not three sequential queries.
Observed PostgreSQL 18.6 diagnostic plan. The partial aggregate's average is rounded: worker outputs were 998 and 1,000 groups, and the leader contributed 1,002. The original report's October result has 991 customers; this full-table count has 1,002.
Check Workers Planned against Workers Launched; a plan can run with fewer workers than expected. The leader may also execute the parallel portion, so two workers do not necessarily mean two participants. EXPLAIN (ANALYZE, VERBOSE) exposes per-worker detail. Compare their rows and elapsed work for imbalance rather than trusting an average.
The inner side of a nested loop is non-parallel, but each participant receives only its share of outer rows. An ordinary hash join within a parallel region can build a separate hash table in every participant; a Parallel Hash shares the build. Similarly, an inner merge-join input and its sort may be repeated. Read below the gather boundary to find divided work and duplicated work separately. More workers do not remove a costly serial finalisation or make summed worker time equal statement latency.
Prepared statements and parameter skew
A prepared statement lets PostgreSQL retain the parsed and analysed request for repeated execution in one session. A custom plan uses the actual parameter values for a particular execution. A generic plan can be reused for different values, saving repeated planning work but losing their particular selectivities.
An all-orders request matches 84,000 rows for customer 1001 and 36 for customer 1002. A plan suited to finding 36 rows need not suit reading 84,000, so compare both parameter classes. These are recorded forced-plan observations, separate from the ten-row history request.
84,000 matching orders
The custom plan sees that 1001 owns most orders. The generic plan uses the same estimate and route for either customer.
Measured forced custom and generic plans for SELECT order_id, placed_at, status FROM orders WHERE customer_id = $1. This retrieves every matching order; it is separate from the ten-row history query. The selector displays recorded plans, not a live database.
Both parameter cases, as text
Customer 1001 matches 84,000 orders. The custom plan scans the table; the generic plan uses a bitmap heap scan. Customer 1002 matches 36 orders. The custom plan uses an index scan; the generic plan uses a bitmap heap scan. A generic plan estimates the same population whichever customer is supplied.
The custom estimates were 84,000 and 36 respectively. The generic plan estimated 120 for either parameter. For the common customer its bitmap heap scan touched all 765 heap blocks, plus the customer index. An accurate common-value list did not help that generic estimate: the plan did not know which customer $1 would be.
Inspecting the plan actually used
PREPARE customer_orders(integer) AS
SELECT order_id, placed_at, status
FROM orders WHERE customer_id = $1;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)
EXECUTE customer_orders(1001);
SELECT name, generic_plans, custom_plans
FROM pg_prepared_statements
WHERE name = 'customer_orders';EXPLAIN EXECUTE shows the plan selected for that execution. A generic condition retains $1; a custom one substitutes the supplied value. The counts in pg_prepared_statements belong to the current session. Reading them on a different pooled connection does not inspect the application's prepared object. Also remember that EXPLAIN ANALYZE EXECUTE executes it and therefore participates in that session's execution history.
Under plan_cache_mode = auto, PostgreSQL initially tries five custom executions and compares their average estimated cost with a generic plan's estimated cost, allowing for repeated planning. This is a cost comparison, not “switch on execution six” and not a comparison of observed elapsed times.
In our first fresh prepared session sequence, five rare executions followed by the common customer remained custom: the view reported zero generic and six custom plans. After deallocating and preparing again, five common executions followed by the rare customer used a generic plan on the sixth: one generic and five custom. Identical SQL and data produced different choices because the prior parameter costs differed.
Testing a prepared-plan repair
Compare forced custom, forced generic and automatic planning for representative values and execution orders. In a disposable session, begin an explicit transaction before using SET LOCAL plan_cache_mode = force_custom_plan or SET LOCAL plan_cache_mode = force_generic_plan. The setting lasts until the transaction ends. Recreate the prepared statement when testing a fresh automatic history.
A targeted custom-plan choice can be worth its planning cost for an expensive, skew-sensitive request. A generic plan can be a sound saving for a stable request whose values suit the same route. A better access path, such as the history index, may also make parameter variation less important. Choose from total planning and execution cost, request frequency and result transfer. Our forced plans establish route differences; their single profiled timings do not justify disabling preparation for the application.
Statistics collection and relevant schema changes can invalidate cached plans. Retain that state in a comparison, and check the driver's preparation behaviour and connection lifetime. The SQL PREPARE example makes the server mechanism explicit. It does not establish that every client uses it in the same way.
Checking the repair against the workload
A repair earns acceptance when the work it was meant to remove disappears and the required results remain correct. The composite history index removed a sort and let Limit stop the search. The MCV list corrected an estimate without removing a scan. The direct report removed repeated aggregates but took longer in its one profiled comparison. Those are three different findings.
Check results as rows with multiplicity and exact values, including the requested order. Include rare and common customers, short and long ranges, ties and empty contributions. For the report rewrite, a line-free eligible order checks the lateral guard; equal-valued lines check that nobody replaced a sum with a distinct sum.
Then alternate ordinary executions of the candidate and baseline, recording enough repetitions to see variation. Include both planning and execution where the request pays them, and consume the same output. Keep cache state and experiment order visible. A plan collected with extra instrumentation and a second execution on cached pages answer different timing questions.
Finally test the actual request mix and concurrency. Extra indexes charge writes as well as reads. A larger memory allowance competes with other operations. Custom planning spends backend time, and a broad report may consume resources that a rare lookup hardly touches. The isolated experiments here identify mechanisms and candidates; they do not establish production throughput or latency.
If the request still waits outside execution, continue with Operating and diagnosing PostgreSQL. Pool waiting, admission, locks and result delivery need evidence at their own boundaries. A well-read plan lets you explain the work PostgreSQL chose, predict a change and check that prediction without confusing it with the rest of the request.