Sub topic 2
Reading query plans with EXPLAIN (ANALYZE, BUFFERS)
Every index decision in PostgreSQL ends with the same question: did the planner use the index, and did it help? EXPLAIN answers it. This chapter explains how to read a plan, how to tell estimates from measurements, and how BUFFERS shows the I/O behind a query's run time.
This chapter assumes you can write SELECT queries with WHERE, JOIN, and ORDER BY, and that you can create tables and insert rows in PostgreSQL. It also assumes you know what an index is: a separate structure that lets PostgreSQL find rows without reading the whole table. The plan output below is illustrative. Your costs, timings, and buffer counts will differ, but the shape should match.
EXPLAIN versus EXPLAIN ANALYZE
EXPLAIN shows the plan the planner chose, without running the query. Every number in it is an estimate.
EXPLAIN ANALYZE runs the query and adds what actually happened: real row counts, real time, and loop counts. This is the version you need when judging an index.
The two forms differ in one way that can cause damage. EXPLAIN ANALYZE really executes the statement, so an UPDATE, DELETE, or INSERT really changes data. Wrap those in a transaction and roll back:
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET status = 'closed' WHERE customer_id = 42;
ROLLBACK;Options go in parentheses and can be combined. These are the ones used most often:
| Option | Effect |
|---|---|
| `ANALYZE` | Runs the query and reports actual rows, time, and loops |
| `BUFFERS` | Reports how many 8 kB pages were found in cache, read, dirtied, or written |
| `VERBOSE` | Adds output column lists and schema-qualified names |
| `SETTINGS` | Lists non-default planner settings that affected the plan |
| `FORMAT JSON` | Emits machine-readable output, useful for plan visualizers |
A table to experiment on
The following script builds the orders table from this tutorial's running example and fills it with 200,000 rows spread over 1,000 customers. The index is created later, so you can compare plans before and after.
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()
);
INSERT INTO orders (customer_id, status, total, created_at)
SELECT 1 + (random() * 999)::int,
CASE WHEN random() < 0.05 THEN 'open' ELSE 'closed' END,
round((random() * 500)::numeric, 2),
now() - (random() * interval '365 days')
FROM generate_series(1, 200000);
ANALYZE orders;ANALYZE orders collects the column statistics the planner relies on. Skip it after a bulk load and the planner works from stale numbers.
Anatomy of a plan
Start with the query and no index on customer_id:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;The output looks like this:
Limit (cost=4130.12..4130.15 rows=10 width=18) (actual time=14.8..14.9 rows=10 loops=1)
Buffers: shared hit=1540
-> Sort (cost=4130.12..4132.62 rows=200 width=18) (actual time=14.8..14.8 rows=10 loops=1)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 26kB
Buffers: shared hit=1540
-> Seq Scan on orders (cost=0.00..4125.00 rows=200 width=18) (actual time=0.05..14.6 rows=197 loops=1)
Filter: (customer_id = 42)
Rows Removed by Filter: 199803
Buffers: shared hit=1540
Planning Time: 0.12 ms
Execution Time: 14.95 msA plan is a tree. Each line starting with -> is a node, and indentation shows parent and child. Data flows from the innermost, most-indented node outward. Read from the bottom up: the Seq Scan produces rows, the Sort orders them, and the Limit keeps ten.
The two parenthesized groups
Each node has two groups of numbers.
The first group is the planner's estimate:
cost=4130.12..4132.62gives startup cost and total cost. Startup cost is the work before the first row can be returned. ASorthas a high startup cost because it must consume all its input first.rows=200is the estimated number of rows this node outputs.width=18is the estimated average row size in bytes.
Cost is in arbitrary planner units, not milliseconds. Compare costs between plans for the same query, and do not convert them to time.
The second group is measured, and it appears only with ANALYZE:
actual time=14.8..14.9gives milliseconds to the first row and to the last row.rows=10is the real number of rows produced.loops=1is how many times the node ran.
Loops and per-loop averages
When a node runs more than once, as the inner side of a nested loop join does, its actual time and rows are averages per loop. Multiply by loops to get totals. A node showing actual time=0.02..0.03 rows=3 loops=500 produced about 1,500 rows and spent roughly 15 ms in total.
Detail lines under a node
Lines such as Filter, Index Cond, and Sort Key explain what the node does. Two matter most for index work:
Index Condis a condition the index itself applied while searching.Filteris a condition checked after rows were fetched.Rows Removed by Filtercounts the rows read and thrown away. A large number there means the node did a lot of work for few results.
In the plan above, 199,803 rows were read and discarded to return 197. That is the signal that an index on customer_id would help.
Scan node types
The scan nodes at the leaves tell you how PostgreSQL reads the table.
| Node | What it does | Typical situation |
|---|---|---|
| `Seq Scan` | Reads every page of the table | Small tables, or queries that need a large share of rows |
| `Index Scan` | Walks the index, then fetches each matching row from the table (the heap) | Few matching rows, or rows needed in index order |
| `Index Only Scan` | Answers from the index alone, without visiting the heap for most rows | All needed columns are in the index and the table's visibility map is current |
| `Bitmap Index Scan` and `Bitmap Heap Scan` | Collects matching row locations from one or more indexes, then reads heap pages in physical order | Medium numbers of matching rows, or combining several indexes |
A Seq Scan is not a failure. Reading a whole table sequentially is efficient, and if a query needs a large fraction of the rows, it beats thousands of random index lookups.
The effect of an index
Now create the multicolumn index and run the same query:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;The plan becomes:
Limit (cost=0.42..42.60 rows=10 width=18) (actual time=0.03..0.06 rows=10 loops=1)
Buffers: shared hit=13
-> Index Scan using orders_customer_created_idx on orders (cost=0.42..845.00 rows=200 width=18) (actual time=0.03..0.05 rows=10 loops=1)
Index Cond: (customer_id = 42)
Buffers: shared hit=13
Planning Time: 0.15 ms
Execution Time: 0.09 msThree things changed:
- The
Sortnode disappeared. The index already stores each customer's rows increated_at DESCorder, so rows arrive pre-sorted. - The scan stopped after 10 rows. The scan's estimated total cost (845.00) is much higher than the
Limitnode's cost (42.60), because the planner knowsLimitwill not read the scan to the end. - Buffers dropped from 1,540 pages to 13.
The query is an Index Scan, not an Index Only Scan, because it selects total, which is not in the index. Each match needs a heap visit. Adding INCLUDE (total) is the fix, covered in the chapter on multicolumn and covering indexes.
What BUFFERS tells you
Run time varies with cache state, concurrent load, and hardware. Buffer counts are more stable, and they show where the work went. Counts are in 8 kB pages:
shared hitmeans the page was already in PostgreSQL's shared buffer cache.shared readmeans the page had to be requested from the operating system, which may or may not have it cached.shared dirtiedandshared writtenshow pages modified or flushed by the query.
On a cold cache, the same plan shows shared read=13 instead of shared hit=13 and runs slower. If two runs of one query differ greatly in time but not in buffer totals, you were measuring the cache, not the plan. Run the query two or three times and compare the stable runs.
Parent nodes include the buffers of their children, so the top line's count is the total for the query. For an Index Only Scan, also read the Heap Fetches line. A high value means the visibility map is out of date and the scan keeps visiting the table. A VACUUM of the table usually fixes it.
Estimated versus actual rows
Compare rows= in the estimate to rows= in the actual group on each node. In the indexed plan, the scan estimated 200 rows and the Limit stopped at 10, which is consistent. In the sequential plan, the estimate was 200 and the actual was 197, which is a good match.
A large mismatch, such as an estimate of 5 rows against an actual of 80,000, means the planner chose its plan on bad information. It might pick a nested loop where a hash join would be better, or ignore a useful index. Common causes are stale statistics (run ANALYZE), correlated columns the planner treats as independent, and conditions on expressions it has no statistics for.
When you see a mismatch, find the lowest node where the estimate first goes wrong. Errors compound upward, so the lowest bad estimate is the cause.
Why the planner might ignore your index
An unused index is usually not a bug. Check these causes in order:
- The table is small. Reading a few pages sequentially costs less than an index lookup.
- The query matches a large share of the table. Random access to many rows loses to a sequential scan.
- The condition does not match the index. A filter on
lower(email)cannot use a plain index onemail. - Statistics are stale, so the planner mis-estimates selectivity.
To test whether an index could be used, disable sequential scans for your session only:
SET enable_seqscan = off;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM orders WHERE status = 'open';
RESET enable_seqscan;This does not forbid sequential scans. It adds a large cost penalty to them. If the index plan is then slower or costs more buffers, the planner was right. Use this as a diagnostic only, never as a production setting.
A reading procedure
The diagram summarizes a repeatable order for reading any plan.
Common mistakes
- Running
EXPLAIN ANALYZEon a write statement without a transaction and rollback. - Judging a query by one cold run. Repeat it and look at buffers as well as time.
- Reading cost as milliseconds.
- Testing on a tiny development table. The planner correctly picks a
Seq Scanthere, and the result tells you nothing about production. - Ignoring
Planning Time. For simple queries on large schemas it can be a visible share of the total.
Exercise
A node in a plan shows Index Scan using orders_customer_created_idx on orders (actual time=0.02..0.04 rows=3 loops=500). Roughly how many rows did this node produce in total, and about how much time did it spend?
Show answer
It produced about 1,500 rows (3 rows x 500 loops). Time per loop is roughly 0.04 ms for the last row, so the node spent about 20 ms in total (0.04 ms x 500). The actual time and rows values are per-loop averages, so you multiply by loops.
Exercise
Your plan shows Seq Scan on orders with Filter: (customer_id = 42) and Rows Removed by Filter: 199803, and the node returned 197 rows. A matching index on customer_id exists, yet the planner did not use it. Name two checks you would make.
Show answer
First, confirm statistics are current by running ANALYZE orders and rerunning the query, because stale statistics can lead the planner to overestimate how many rows match. Second, run SET enable_seqscan = off in your session and compare the index plan's cost and buffers to the sequential plan. If the index plan reads fewer buffers, the planner's estimate is off. If it reads more, the sequential scan was the better choice.