Sub topic 13
Finding the node that costs the most
This chapter assumes you can run EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL and read a plan as a tree of nodes. It also assumes you know what estimated and actual row counts are. Here you turn a long plan into one answer: which node should I change first?
Why the biggest number is often the wrong one
A plan can have a dozen nodes, and every one reports a time. The time on the top node is always the largest, because it includes all the work below it. If you look for the largest number, you will always pick the root, and that tells you nothing.
To find a bottleneck you need the time each node spends itself. This is the exclusive time. It is the node's own time minus the time of its children.
A plan to work with
This query lists the ten customers with the most orders this year. It is the same query used earlier in the tutorial.
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, count(*) AS order_count
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= DATE '2026-01-01'
GROUP BY c.name
ORDER BY order_count DESC
LIMIT 10;A plan for it might look like this. The cost and width values are removed so the timing is easier to follow.
Limit (actual time=412.118..412.121 rows=10 loops=1)
-> Sort (actual time=412.116..412.117 rows=10 loops=1)
Sort Key: (count(*)) DESC
Sort Method: top-N heapsort Memory: 26kB
-> HashAggregate (actual time=409.800..411.200 rows=48000 loops=1)
Group Key: c.name
-> Hash Join (actual time=21.400..350.200 rows=640000 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (actual time=0.030..260.500 rows=640000 loops=1)
Filter: (created_at >= '2026-01-01'::date)
Rows Removed by Filter: 1360000
Buffers: shared hit=1200 read=18300
-> Hash (actual time=21.000..21.000 rows=50000 loops=1)
Buckets: 65536 Batches: 1 Memory Usage: 3100kB
-> Seq Scan on customers c (actual time=0.010..9.500 rows=50000 loops=1)
Buffers: shared hit=640
Planning Time: 0.350 ms
Execution Time: 412.400 msStep 1: Read the actual time correctly
Each node shows actual time=A..B. A is the time until the node returned its first row. B is the time until it returned its last row. Both are in milliseconds.
Two rules decide how to use B:
Bincludes the time spent in every child node. It is inclusive time.Bis an average per loop. Ifloopsis greater than 1, multiplyBbyloopsto get the node's total time.
The second rule matters most for the inner side of a nested loop. Look at this node:
-> Index Scan using orders_customer_id_idx on orders o
(actual time=0.015..0.021 rows=12 loops=50000)It looks fast, at 0.021 ms. But it ran 50,000 times, so the total is about 0.021 × 50,000 = 1,050 ms. The rows are also per loop. This node produced about 12 × 50,000 = 600,000 rows in total.
Step 2: Compute exclusive time
Work from the leaves upward and subtract each node's children from its own end time. For the plan above:
| Node | Inclusive time (ms) | Children (ms) | Exclusive time (ms) |
|---|---|---|---|
| Seq Scan on orders | 260.5 | none | about 260 |
| Seq Scan on customers | 9.5 | none | about 10 |
| Hash | 21.0 | 9.5 | about 11 |
| Hash Join | 350.2 | 260.5 and 21.0 | about 69 |
| HashAggregate | 411.2 | 350.2 | about 61 |
| Sort | 412.1 | 411.2 | about 1 |
| Limit | 412.1 | 412.1 | about 0 |
The sequential scan on orders accounts for about 260 of the 412 ms, which is roughly 63 percent. That is the node to examine first.
This subtraction is approximate. A hash join builds its hash table before it returns any rows, so the timings of its children overlap with its own start time. The numbers are good enough to rank nodes. They are not exact accounting.
Step 3: Ask why that node is slow
Once you have a candidate, look at the lines attached to it. Four signals are worth checking.
Estimate against actual
If the planner expected 500 rows and got 640,000, the planner probably chose the wrong join method or scan type. The slow node may be a symptom of a bad estimate lower in the tree. Fix the estimate first, using ANALYZE or extended statistics, and then look at the plan again.
Rows removed by filter
Rows Removed by Filter: 1360000 means the scan read 2,000,000 rows to keep 640,000. When most rows are discarded, an index on the filtered column may help. Here 68 percent are discarded, but the remaining 32 percent is still a large share of the table. An index would help less than it first appears, because the query needs a large part of the table anyway.
Buffers
shared hit=1200 read=18300 means the node found 1,200 pages in PostgreSQL's cache and fetched 18,300 pages from the operating system or disk. Each page is 8 kB by default, so this scan read about 143 MB. A node with a large read count is paying for I/O. Run the query a second time. If the read count drops and the time falls with it, the first run was slow because the cache was cold, and the plan itself may be fine.
Memory and spills
Sort and hash nodes report how they used memory. These lines mean trouble:
Sort Method: external merge Disk: 84000kBmeans the sort did not fit inwork_memand wrote temporary files.Batches: 16on a hash node means the hash table was split into batches and spilled to disk.Batches: 1is the good case.
The plan above shows top-N heapsort Memory: 26kB and Batches: 1, so neither node spilled.
Other places time can hide
Time sometimes appears outside the node tree.
- Planning Time is reported separately. A short query on a table with many partitions can spend more time planning than executing.
- JIT lines at the bottom of a plan report compile time. For queries under a second, JIT can cost more than it saves.
- Trigger lines appear after
UPDATE,INSERT, orDELETEstatements. Foreign key checks and user triggers show up there, not in the tree. - Parallel nodes such as
GathershowWorkers Launched. Per-worker timings are averaged, so a node's real total effort can be larger than its time suggests.
Choosing what to do
Match the evidence to a fix. This table covers the common cases.
| What you see on the costly node | Likely cause | First thing to try |
|---|---|---|
| Estimate far from actual rows | Stale or missing statistics | `ANALYZE` the table, then consider extended statistics |
| Seq Scan, most rows removed by filter | No usable index | Add an index on the filtered column |
| Seq Scan, few rows removed | Query needs most of the table | Accept it, or narrow the query |
| Index Scan with a large `loops` value | Nested loop over many outer rows | Check the outer estimate, or rewrite so a hash join is possible |
| Sort with `Disk` in the method | `work_mem` too small, or sorting too many rows | Add an index that returns rows in order, or filter earlier |
| Hash with many batches | Hash table larger than `work_mem` | Reduce the input rows, or raise `work_mem` for that session |
| High `read` in Buffers | Cold cache or too many pages | Re-run to confirm, then reduce pages read |
For the example, the best change is probably not an index on created_at, because the query touches nearly a third of the table. Reading fewer pages is a better goal. Check whether the table is bloated, whether a narrower covering index would allow an index-only scan, or whether the report can use a pre-aggregated table.
Check that the change worked
After each change, run the same EXPLAIN (ANALYZE, BUFFERS) again and compare three things: the exclusive time of the node you changed, the total Execution Time, and the read counts. Change one thing at a time. If you add an index and refresh statistics together, you cannot tell which one helped.
Exercise
A plan has an inner node Index Scan using items_order_id_idx on items (actual time=0.004..0.006 rows=3 loops=200000). Its parent is a Nested Loop with actual time=0.050..1480.000 rows=600000 loops=1, and the outer child of that Nested Loop took 310 ms in total. About how much time did the inner index scan use in total, and is it the main cost of this join?
Show answer
The inner scan's total time is the per-loop time multiplied by loops, so about 0.006 × 200,000 = 1,200 ms. It is the main cost. The Nested Loop's 1,480 ms minus the 310 ms outer child leaves about 1,170 ms, which matches the inner scan's 1,200 ms to within the rounding of the per-loop figure. The 0.006 ms per call looks small, but the 200,000 repeats make it the largest cost. Check whether the outer row estimate was too low, which can lead the planner to choose a nested loop when a hash join would be cheaper.