Sub topic 14
Reading query plans with EXPLAIN
This chapter assumes you can write basic SQL (SELECT, WHERE, JOIN, ORDER BY) and can run statements in psql or the pgAdmin Query Tool. You should know what an index is at a basic level. By the end you will be able to run EXPLAIN, read the plan tree, and spot the usual signs of a slow query.
What a query plan is
When you send a query, PostgreSQL does not run it as written. The planner picks a strategy: which tables to scan, whether to use an index, which join method to use, and in what order. The result is a query plan, a tree of steps called plan nodes. EXPLAIN shows you that tree.
There are two things to keep apart:
EXPLAINalone shows the plan the planner chose and its estimates. The query is not run.EXPLAIN ANALYZEruns the query and adds the real row counts and timings next to the estimates.
Your first plan
The examples use an orders table with a customer_id column. Run this in psql or the Query Tool:
EXPLAIN
SELECT * FROM orders WHERE customer_id = 42;A typical result when there is no index on customer_id:
QUERY PLAN
---------------------------------------------------------
Seq Scan on orders (cost=0.00..1834.00 rows=12 width=48)
Filter: (customer_id = 42)Read it in three parts:
Seq Scan on ordersis the node type. A sequential scan reads every row of the table.cost=0.00..1834.00is the planner's cost estimate. The first number is the cost before the first row can be returned. The second is the total cost. Cost is in arbitrary units, not milliseconds. Use it to compare plans, not to predict time.rows=12 width=48is the estimated number of rows returned and the estimated average row size in bytes.
The indented Filter: line shows the condition applied to each row as it is read.
Estimates versus actual numbers
Add ANALYZE to get real measurements. Use BUFFERS to see how much data was read.
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;
ROLLBACK;Example output:
Seq Scan on orders (cost=0.00..1834.00 rows=12 width=48) (actual time=0.015..9.870 rows=15 loops=1)
Filter: (customer_id = 42)
Rows Removed by Filter: 99985
Buffers: shared hit=334 read=0
Planning Time: 0.080 ms
Execution Time: 9.910 msThe second parenthesis holds the measured values:
actual time=0.015..9.870is the time in milliseconds to the first row and to the last row.rows=15is the actual row count. Compare it with the estimate of 12. A close match means the planner had good statistics.loops=1is how many times the node ran. For nodes inside a nested loop, actual time and rows are averages per loop, so multiply byloopsto get the total.Rows Removed by Filter: 99985shows the scan read about 100,000 rows to keep 15. That is a hint that an index could help.Buffers: shared hit=334counts 8 kB pages found in PostgreSQL's cache (hit) or fetched from outside it (read).
Reading the tree
Plans are trees. Child nodes are indented and feed rows to their parent. Read from the most indented node outward. The leaf nodes read tables, and the nodes above them combine, sort or aggregate the rows.
EXPLAIN
SELECT c.name, count(*)
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'NO'
GROUP BY c.name; HashAggregate (cost=2105.10..2107.60 rows=250 width=40)
Group Key: c.name
-> Hash Join (cost=14.20..2050.00 rows=11000 width=32)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (cost=0.00..1584.00 rows=100000 width=4)
-> Hash (cost=12.50..12.50 rows=136 width=36)
-> Seq Scan on customers c (cost=0.00..12.50 rows=136 width=36)
Filter: (country = 'NO'::text)Here the planner scans customers, filters it, and builds an in-memory hash table. It then scans orders and probes the hash table for each row. Finally it groups the joined rows.
Common node types
| Node | What it does | When it appears |
|---|---|---|
| Seq Scan | Reads the whole table | No usable index, or most rows are needed |
| Index Scan | Walks an index, then fetches matching rows from the table | Selective filter on an indexed column |
| Index Only Scan | Answers from the index alone | All needed columns are in the index and the table's visibility map is current |
| Bitmap Heap Scan | Collects matching row locations from an index, then reads the table pages in order | Medium number of matches |
| Nested Loop | For each outer row, looks up matching inner rows | Small outer side, or indexed inner side |
| Hash Join | Builds a hash table of one side and probes it with the other | Larger, unsorted inputs |
| Merge Join | Merges two sorted inputs | Inputs already sorted, for example by an index |
| Sort | Orders rows | `ORDER BY`, merge joins, some aggregates |
A sequential scan is not automatically bad. On a small table, or when a query needs most of the rows, it is the cheapest choice. The planner often skips an index for exactly that reason.
Seeing an index change the plan
Create an index and run the plan again:
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42; Index Scan using orders_customer_id_idx on orders (cost=0.29..18.40 rows=12 width=48) (actual time=0.020..0.045 rows=15 loops=1)
Index Cond: (customer_id = 42)
Buffers: shared hit=17
Planning Time: 0.110 ms
Execution Time: 0.070 msThe cost fell from 1834 to 18, and the time from about 9.9 ms to 0.07 ms. The filter became an Index Cond. Only 17 buffers were touched instead of 334.
ANALYZE orders; refreshes the table statistics that the planner uses for its row estimates. Without fresh statistics, the planner can pick a poor plan.
Warning signs in a plan
Look for these when a query is slow:
- Large gap between estimated and actual rows. For example,
rows=10estimated androws=50000actual. The planner chose its strategy on wrong information. RunANALYZEon the table first. If the gap remains, the columns may be correlated or skewed in ways default statistics miss. - Large
Rows Removed by Filter. The node reads much more than it keeps. An index on the filtered column may help. - Seq Scan on a big table with a selective filter. Check whether an index exists, and whether the filter wraps the column in a function, such as
WHERE lower(email) = '[email protected]'. A plain index onemailcannot serve that condition. - Sort with
Sort Method: external merge Disk. The sort did not fit inwork_memand spilled to disk. - Nested Loop with a large
loopsvalue. An inner node run many thousands of times can dominate the total time. - High
readcounts inBuffers. The query went outside PostgreSQL's cache to get its data. A repeat run may be faster, so compare runs fairly.
Useful options
Options go in parentheses after EXPLAIN:
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, FORMAT TEXT)
SELECT * FROM orders WHERE customer_id = 42;ANALYZEruns the query and reports actual rows and times.BUFFERSreports page counts for cache hits, reads and writes.VERBOSElists the output columns of each node.FORMATcan beTEXT(default),JSON,XMLorYAML. JSON is useful for tools that parse plans.
Timing every node adds overhead, so ANALYZE times are slightly higher than a normal run, most noticeably for queries with many cheap node executions.
Safe use with data-changing statements
For INSERT, UPDATE, DELETE and MERGE, always use a transaction you roll back:
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET status = 'shipped' WHERE customer_id = 42;
ROLLBACK;The update runs, so you get real timings, and ROLLBACK discards the change. Locks are held until the rollback, so do this on a production system with care. A plain EXPLAIN without ANALYZE never runs the statement and is always safe.
Reading plans in psql and pgAdmin
In psql the plan prints as text. Turn on \timing on if you also want the client-side round-trip time, which includes network delay that Execution Time does not.
In the pgAdmin Query Tool, select the query and use the Explain button for the estimated plan, or Explain Analyze for the measured plan. The results show a Graphical tab and an Analysis tab, with the text output available as well. The Graphical view draws each node as an icon with arrows showing row flow, and hovering over a node shows its cost, rows and timing. The Analysis tab lists nodes sorted by time, which helps you find the slow one quickly. The graphical view is easy to scan, but the text plan gives you every detail and is easier to paste into a bug report or a question.
Common mistakes
- Running
EXPLAIN ANALYZEon a destructive statement without a rollback. - Treating cost as time. Cost units are only meaningful relative to other plans for the same query.
- Testing on a tiny development table. The planner chooses different plans for small and large tables, so a plan seen on 100 rows may not match production.
- Adding an index because of a Seq Scan without checking whether the query needs most of the table anyway.
- Comparing a cold first run with a warm second run and concluding that a change helped.
Exercise
A plan shows Seq Scan on orders (cost=0.00..1834.00 rows=12 width=48) (actual time=0.015..9.870 rows=15 loops=1) with Rows Removed by Filter: 99985. What does this tell you, and what is a reasonable next step?
Show answer
The scan read about 100,000 rows to return 15, so almost all the work was discarded. The estimate (12) is close to the actual count (15), so statistics are fine. A reasonable next step is to create an index on the filtered column, run ANALYZE on the table, and run EXPLAIN (ANALYZE, BUFFERS) again to check that the plan changes to an Index Scan with a lower time.
Exercise
Why should you wrap EXPLAIN ANALYZE of an UPDATE in BEGIN and ROLLBACK?
Show answer
EXPLAIN ANALYZE executes the statement, so the update would really change the data. Running it inside a transaction that you roll back gives real timings and discards the changes.