Sub topic 14
Checking plans with EXPLAIN
This chapter assumes you have the schema from the earlier chapters (authors, books, book_authors, readings) and the two foreign-key indexes from the indexing chapter. You should be comfortable with joins and CREATE INDEX. By the end you will be able to read a plan, tell whether an index was used, and spot an estimate that is wrong.
What EXPLAIN shows
PostgreSQL does not run a query as you wrote it. The planner picks a strategy: which tables to read first, how to read them, and how to join them. EXPLAIN prints that strategy as a tree of nodes.
There are two forms:
EXPLAIN queryshows the plan the planner chose and its cost estimates. The query is not run.EXPLAIN (ANALYZE) queryruns the query, then shows the plan with real timings and row counts next to the estimates.
A dataset big enough to matter
The planner compares costs. On a table with ten rows, reading everything is always cheapest, so the plan tells you nothing. Use a scratch database and load synthetic data. The script assumes empty tables, so the identity columns start at 1.
INSERT INTO authors (name)
SELECT 'Author ' || g FROM generate_series(1, 1000) AS g;
INSERT INTO books (title, isbn13, published_year, page_count)
SELECT 'Book ' || g,
lpad(g::text, 13, '0'),
1950 + (g % 70),
100 + (g % 400)
FROM generate_series(1, 100000) AS g;
INSERT INTO book_authors (book_id, author_id)
SELECT book_id, (book_id % 1000) + 1
FROM books;
ANALYZE authors;
ANALYZE books;
ANALYZE book_authors;ANALYZE (the command, not the EXPLAIN option) samples each table and stores statistics: row counts, value distributions, and how common each value is. The planner's estimates come from these statistics. Autovacuum normally refreshes them, but after a bulk load you should run it yourself.
Reading a plan
Start with a query that has no helpful index. Drop the foreign-key index from the indexing chapter and look at the plan:
DROP INDEX IF EXISTS book_authors_author_id_idx;
EXPLAIN (ANALYZE)
SELECT b.title
FROM books b
JOIN book_authors ba USING (book_id)
WHERE ba.author_id = 1;The output looks like this. Your numbers will differ, but the shape should match.
Hash Join (cost=2.35..2125.20 rows=100 width=11) (actual time=0.060..14.200 rows=100 loops=1)
Hash Cond: (b.book_id = ba.book_id)
-> Seq Scan on books b (cost=0.00..1541.00 rows=100000 width=19) (actual time=0.010..6.900 rows=100000 loops=1)
-> Hash (cost=1.10..1.10 rows=100 width=8) (actual time=0.040..0.040 rows=100 loops=1)
-> Seq Scan on book_authors ba (cost=0.00..1.10 rows=100 width=8) (actual time=0.010..9.800 rows=100 loops=1)
Filter: (author_id = 1)
Rows Removed by Filter: 99900
Planning Time: 0.250 ms
Execution Time: 14.300 msRead it from the innermost, most indented nodes outward. Each node reports:
cost=a..b: the planner's estimate in arbitrary units.ais the cost before the first row can be returned, andbis the cost to return all rows. Only compare costs within one database and one query.rows: the estimated number of rows the node returns.width: the estimated average row size in bytes.actual time=a..b: milliseconds to the first row and to the last row, only withANALYZE.actual rowsandloops: how many rows came out, and how many times the node ran. Time and rows are averages per loop, so multiply byloopsfor totals.Rows Removed by Filter: rows read and thrown away. A large number here is the clearest sign that an index could help.
The Seq Scan on book_authors read every row and discarded 99,900 of them. The primary key on (book_id, author_id) cannot help here, because its leading column is book_id. A B-tree index only supports lookups that constrain its leading columns.
Recreating the index and comparing
CREATE INDEX book_authors_author_id_idx ON book_authors (author_id);
ANALYZE book_authors;
EXPLAIN (ANALYZE)
SELECT b.title
FROM books b
JOIN book_authors ba USING (book_id)
WHERE ba.author_id = 1;Nested Loop (cost=4.80..420.50 rows=100 width=11) (actual time=0.060..0.520 rows=100 loops=1)
-> Bitmap Heap Scan on book_authors ba (cost=4.50..120.00 rows=100 width=8) (actual time=0.040..0.090 rows=100 loops=1)
Recheck Cond: (author_id = 1)
Heap Blocks: exact=1
-> Bitmap Index Scan on book_authors_author_id_idx (cost=0.00..4.48 rows=100 width=0) (actual time=0.030..0.030 rows=100 loops=1)
Index Cond: (author_id = 1)
-> Index Scan using books_pkey on books b (cost=0.29..3.00 rows=1 width=19) (actual time=0.003..0.004 rows=1 loops=100)
Index Cond: (book_id = ba.book_id)
Planning Time: 0.300 ms
Execution Time: 0.620 msThe plan changed shape, not just speed. The planner now finds the 100 link rows through the new index, then looks up each book by primary key. The loops=100 on the inner scan shows that lookup running once per link row.
Common node types
| Node | Meaning | When it is a good choice |
|---|---|---|
| Seq Scan | Reads the whole table | Small tables, or queries that need most rows |
| Index Scan | Walks an index, then fetches each row from the table | Few matching rows |
| Index Only Scan | Answers from the index alone | The index holds every needed column and the table is recently vacuumed |
| Bitmap Index Scan and Bitmap Heap Scan | Collects matching row locations, then reads the table pages in order | A moderate number of matches |
| Nested Loop | For each outer row, probe the inner side | Small outer side with an indexed inner side |
| Hash Join | Builds a hash table from one input and probes it | Larger inputs with equality joins |
| Merge Join | Merges two sorted inputs | Inputs already sorted, often by an index |
Estimates against actuals
Compare rows= (estimated) with actual rows=. When they are close, the planner understood your data. When they differ by a factor of ten or more, the planner may have picked a poor join order or join method. Common causes:
- Stale statistics. Run
ANALYZEon the table. - Correlated columns. The planner treats conditions on different columns as independent. If they are not, it underestimates the matching rows.
- Expressions the statistics do not cover, such as
WHERE lower(title) = 'x'.
An estimate that is wrong everywhere in the tree is a statistics problem. An estimate that is wrong at one node points to that node's condition.
Adding BUFFERS
Timings vary with caching. BUFFERS adds I/O counts that are more stable between runs:
EXPLAIN (ANALYZE, BUFFERS)
SELECT title FROM books WHERE isbn13 = '0000000000042';Each node gains a line such as Buffers: shared hit=4. A hit was served from PostgreSQL's cache, and a read came from the operating system or disk. If the second run of a query shows all hits and the first showed reads, the first run's slowness was cold cache, not a plan problem.
Explaining writes safely
The unique constraint on isbn13 created an index named books_isbn13_key. To see how an update finds its row without keeping the change:
BEGIN;
EXPLAIN (ANALYZE)
UPDATE books SET page_count = page_count + 1
WHERE isbn13 = '0000000000042';
ROLLBACK;The plan should show an Index Scan using books_isbn13_key under the Update node. The same pattern works for the ON CONFLICT upsert from the earlier chapter.
Testing whether the planner could use an index
If you expect an index scan and get a Seq Scan, check in this order:
- Is the index on the column's leading position, and does the query use the same expression?
- Are the statistics fresh?
- Would the query return a large share of the table anyway?
To test whether an index scan would be cheaper, you can discourage sequential scans for one session:
SET enable_seqscan = off;
EXPLAIN (ANALYZE)
SELECT title FROM books WHERE published_year = 1999;
RESET enable_seqscan;This does not forbid sequential scans. It adds a large penalty to their cost. Use it only as a diagnostic, never in application code or in postgresql.conf. If the forced index plan is slower, the planner was right.
A workflow
Exercises
Exercise
A query's plan shows Seq Scan on readings, with Rows Removed by Filter: 499,000 and actual rows=1000. The filter is status = 'finished'. What does this tell you, and what would you check before adding an index?
Show answer
The scan read about 500,000 rows to return 1,000, so an index on status could avoid most of that work. Before adding it, check how the planner's estimated rows compare with the actual rows, and whether the query is run often enough to justify the index's write cost. If finished were the majority of rows, the scan would be correct and an index would not help.
Exercise
Why does EXPLAIN (ANALYZE) DELETE FROM readings WHERE rating IS NULL; need special care, and how do you run it safely?
Show answer
ANALYZE executes the statement, so the rows are actually deleted. Run BEGIN;, then the EXPLAIN (ANALYZE) DELETE ... statement, then ROLLBACK; so the plan is reported and the deletion is undone.
Exercise
In a plan, an inner Index Scan shows actual time=0.003..0.004 rows=1 loops=100. Roughly how much time did that node take in total, and how many rows did it return in total?
Show answer
The time and row figures are per loop, so multiply by 100. The node took roughly 0.4 ms in total (about 0.004 ms times 100) and returned about 100 rows.