Sub topic 2
Reading Query Plans with `EXPLAIN (ANALYZE, BUFFERS)`
This chapter assumes you know basic SELECT, WHERE, JOIN, and ORDER BY syntax. You should also know how to create PostgreSQL tables and indexes.
An index can make a query faster, but creating one does not guarantee that PostgreSQL will use it. The query planner compares possible strategies and estimates their cost. EXPLAIN shows the selected strategy. EXPLAIN ANALYZE also runs the query and reports what actually happened.
Start with an estimated plan
Use EXPLAIN when you want to inspect a plan without running the query:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10, 2),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;The output contains plan nodes. A node is one operation, such as scanning a table, reading an index, filtering rows, sorting, or joining tables. Nodes are nested because the output of one operation becomes the input to another.
A plan might contain an Index Scan below a Limit node:
Limit (cost=0.42..8.55 rows=10 width=16)
-> Index Scan using orders_customer_created_idx on orders
(cost=0.42..81.70 rows=100 width=16)
Index Cond: (customer_id = 42)The Index Scan can find rows for customer_id = 42 in index order. Because the index stores created_at in descending order, PostgreSQL can also satisfy the ORDER BY without a separate sort.
Read the main plan fields
A node commonly shows four estimates:
cost=start..totalis the planner's estimated work. These are cost units, not milliseconds.rowsis the estimated number of rows produced by the node.widthis the estimated average row size in bytes.- The node name identifies the operation, such as
Seq Scan,Index Scan, orBitmap Heap Scan.
A Seq Scan reads a table from beginning to end. It can be the best choice when the query needs many rows, when the table is small, or when the filter matches a large percentage of the table. An index scan is not automatically faster because it may require many scattered table reads.
The planner's estimates depend on table statistics. After a large data change, run:
ANALYZE orders;If estimated row counts differ greatly from the real counts, stale or insufficient statistics may cause a poor plan.
Compare estimates with execution
EXPLAIN ANALYZE executes the statement and adds actual timing and row counts:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;Typical output looks like this:
Limit (cost=0.42..8.55 rows=10 width=16)
(actual time=0.030..0.041 rows=10 loops=1)
Buffers: shared hit=4
-> Index Scan using orders_customer_created_idx on orders
(cost=0.42..81.70 rows=100 width=16)
(actual time=0.029..0.038 rows=10 loops=1)
Index Cond: (customer_id = 42)
Buffers: shared hit=4
Planning Time: 0.180 ms
Execution Time: 0.070 msactual time is measured in milliseconds. The first value is when the node produced its first row, and the second is when it finished. rows is the number produced per loop. Multiply the displayed row count by loops when interpreting repeated nodes.
BUFFERS reports data-page activity. A shared hit means PostgreSQL found a page in its shared buffer cache. A shared read means it had to read the page from storage. A hit is usually cheaper than a read, although cache state changes between executions.
Follow a plan from the bottom up
Read the innermost scan first, then follow how its rows move upward. A Filter condition is applied after a node produces rows. An Index Cond is used to locate entries through the index. This distinction matters: a plan that scans many index entries and rejects most of them with a filter may need a better index.
PostgreSQL may still choose Seq Scan even when a suitable index exists. Common reasons include low selectivity, a small table, inaccurate statistics, or the cost of random table access. Check the plan and row estimates before changing an index.
Exercise
A plan estimates 1,000 rows but EXPLAIN ANALYZE reports 1,000,000 rows. What should you check first?
Show answer
Run ANALYZE on the relevant table, then inspect the plan again. A large estimate error can cause the planner to choose the wrong scan or join strategy.