Sub topic 14
Reading Query Plans with EXPLAIN
Assume you know basic SELECT, WHERE, JOIN, and indexes. You also need access to a PostgreSQL database with a table such as orders. A query plan is PostgreSQL's chosen method for finding and combining rows. Reading plans helps explain why a query is slow.
Start with EXPLAIN
EXPLAIN shows the plan without running the query:
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;A typical result might contain:
Index Scan using orders_customer_id_idx on orders
(cost=0.29..8.31 rows=3 width=48)
Index Cond: (customer_id = 42)The plan is a tree. PostgreSQL usually performs the lower, indented steps first and passes their rows to the step above them.
| Plan value | Meaning |
|---|---|
| `cost=0.29..8.31` | Estimated startup cost and total cost |
| `rows=3` | Estimated number of rows produced |
| `width=48` | Estimated average row size in bytes |
| `Index Cond` | Condition used to search the index |
Cost is an internal unit, not milliseconds. Use it to compare alternative plans within the same database. A lower estimated cost usually indicates a cheaper plan, but the estimate can be wrong when table statistics are stale.
See what actually happened
EXPLAIN ANALYZE runs the query and adds measured values:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = 42;Look for values such as:
(actual time=0.040..0.052 rows=3 loops=1)
Buffers: shared hit=4actual time is measured in milliseconds. rows is the number actually returned by one loop. loops shows how many times PostgreSQL repeated that node. For example, a node reporting rows=10 loops=100 processed about 1,000 rows in total.
Buffers: shared hit means PostgreSQL found pages in its buffer cache. A read means it had to read pages from storage. Buffer counts help distinguish CPU work from data access.
Recognize common plan nodes
Seq Scanreads a table from beginning to end. This can be efficient for small tables or queries that return many rows.Index Scanuses an index to find matching table rows. It often helps selective filters.Bitmap Index ScanandBitmap Heap Scancollect many matching locations before reading the table.Nested Looprepeats an inner operation for each row from an outer operation.Hash Joinbuilds a hash table from one input and probes it with the other.Sortorders rows and can use memory or temporary disk space.Aggregatecalculates values such asCOUNTorSUM.
Compare estimated and actual rows. A large difference, such as rows=10 versus actual rows=100000, can lead PostgreSQL to choose a poor join or scan method. Run ANALYZE orders; to refresh statistics before investigating further.
> callout warning > EXPLAIN ANALYZE executes the statement. For UPDATE, DELETE, or INSERT, test inside a transaction and roll it back. > > ``sql > BEGIN; > EXPLAIN (ANALYZE, BUFFERS) > DELETE FROM orders > WHERE customer_id = 42; > ROLLBACK; > ``
Use EXPLAIN in pgAdmin
In pgAdmin's Query Tool, enter a query and select Explain to display a graphical plan. Select Explain Analyze when you want measured execution data. The graphical view helps you follow branches, while the text view makes exact costs, row counts, and buffer statistics easier to compare.
Exercise
A plan estimates 20 rows but returns 50,000 rows. What should you investigate first?
Show answer
Check whether table statistics are stale or whether the filter's data distribution is unusual. Run ANALYZE on the relevant table, then compare the new plan and actual row counts.