Sub topic 14
Checking Plans with EXPLAIN
Prerequisites and purpose
Assume you know basic SQL joins and have a PostgreSQL database containing the book-tracking tables. You should also know that an index is a data structure that helps PostgreSQL find rows without reading an entire table.
A query plan is PostgreSQL’s chosen method for executing a query. It describes operations such as scanning a table, looking up rows through an index, joining tables, and sorting results. EXPLAIN displays this plan without running the query.
Use EXPLAIN when a query is slower than expected or when you want to check whether an index can help.
Reading a basic plan
Suppose the database has an index on book_authors.author_id. Ask PostgreSQL how it would find books written by author 1:
EXPLAIN
SELECT b.title
FROM books AS b
JOIN book_authors AS ba USING (book_id)
WHERE ba.author_id = 1;A plan might contain operations like these:
| Plan operation | Meaning |
|---|---|
| Seq Scan | Read every row in a table |
| Index Scan | Use an index to find matching rows |
| Hash Join | Build a lookup structure and join matching rows |
| Sort | Arrange rows into the requested order |
A plan node usually includes estimated cost, estimated output rows, and estimated width. Cost is an internal unit that lets PostgreSQL compare strategies. It is not milliseconds. The first cost is the estimated startup cost, and the second is the estimated total cost.
PostgreSQL might choose a sequential scan even when an index exists. That is reasonable for a small table because reading the whole table can cost less than jumping through an index for many rows.
Measuring actual execution
Add ANALYZE to execute the query and include observed timing and row counts:
EXPLAIN (ANALYZE, BUFFERS)
SELECT b.title
FROM books AS b
JOIN book_authors AS ba USING (book_id)
WHERE ba.author_id = 1;Important fields include:
actual time: observed start and end time for a plan node, in milliseconds.actual rows: rows produced by the node.loops: how many times PostgreSQL ran the node.Buffers: pages read from storage or found in memory.
Compare estimated rows with actual rows. A large difference can lead PostgreSQL to choose a poor join strategy. Refresh statistics when data changes substantially:
ANALYZE books;
ANALYZE book_authors;The plan is easier to reason about as a flow:
Common errors
Do not judge performance from estimated cost alone. Use EXPLAIN (ANALYZE) and test with realistic data. Do not add indexes for every column. Indexes consume storage and make writes more expensive. Check the queries that matter, then verify whether the chosen plan improves.
Exercise
Why might PostgreSQL use a sequential scan for a filtered query even when a suitable index exists?
Show answer
If the table is small or the filter matches many rows, reading the whole table may have a lower estimated cost than using the index.