Sub topic 6
Reading query plans with EXPLAIN
This chapter assumes you can write basic SELECT queries and know what a B-tree index is, including how a lookup walks from root to leaf. It also assumes you know what a sequential scan is. The examples use PostgreSQL. MySQL, SQL Server, and Oracle have equivalent tools with different output formats.
A query plan is the planner's chosen strategy for running a query. EXPLAIN prints that plan. Reading plans is how you check whether an index is being used, and why it isn't when it should be.
Setup
Run this once to get a table large enough for the planner to prefer indexes in some cases.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
INSERT INTO orders (id, customer_id, status, created_at, total_cents)
SELECT g,
(g % 10000) + 1,
CASE WHEN g % 20 = 0 THEN 'open' ELSE 'closed' END,
timestamptz '2026-01-01' + (g * interval '1 minute'),
(g % 5000) + 100
FROM generate_series(1, 1000000) AS g;
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE orders;ANALYZE collects the statistics the planner uses to estimate row counts. Without it, the estimates in the plans below would be unreliable.
EXPLAIN versus EXPLAIN ANALYZE
Plain EXPLAIN shows the plan and the planner's estimates. It does not run the query.
EXPLAIN ANALYZE runs the query and adds measured values next to the estimates: real time, real row counts, and loop counts. Comparing estimated and actual values is the main debugging technique.
EXPLAIN SELECT * FROM orders WHERE id = 42;
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE id = 42;BUFFERS adds how many 8 KB pages were read from cache (shared hit) or from disk (read). Page counts are often a steadier measure than time, because time varies with cache state and machine load.
Anatomy of a plan
A plan is a tree of nodes. Each node does one job, such as scanning a table or joining two inputs. Indentation and -> arrows show nesting. A node pulls rows from its children, so the innermost nodes run first.
This is an illustrative plan for a primary-key lookup. Your numbers will differ.
Index Scan using orders_pkey on orders (cost=0.42..8.44 rows=1 width=33) (actual time=0.025..0.026 rows=1 loops=1)
Index Cond: (id = 42)
Planning Time: 0.110 ms
Execution Time: 0.045 msEach part means the following:
- Node type (
Index Scan using orders_pkey): how rows are fetched and which index is used. - cost=0.42..8.44: estimated cost in arbitrary planner units. The first number is the startup cost before the first row can be returned. The second is the total cost. Costs are only comparable between plans for the same server settings, not across machines or in seconds.
- rows=1: the estimated number of rows this node produces.
- width=33: the estimated average row size in bytes.
- actual time=0.025..0.026: measured milliseconds to the first row and to the last row (only with
ANALYZE). - loops=1: how many times the node ran. Actual time and rows are averages per loop, so multiply by
loopsfor totals. This matters on the inner side of a nested-loop join. - Index Cond: the condition applied inside the index. A
Filterline is different, as shown below.
The scan nodes you will see most
| Node | What it does | Typical situation |
|---|---|---|
| Seq Scan | Reads every page of the table | No usable index, tiny table, or a query that returns a large fraction of rows |
| Index Scan | Walks the index, then fetches each matching row from the table | A small number of rows, or order matters |
| Index Only Scan | Answers from the index without reading the table, for pages marked all-visible | Covering index with a recently vacuumed table |
| Bitmap Index Scan + Bitmap Heap Scan | Collects matching row locations from the index, sorts them by page, then reads the table in page order | A medium number of matches, or combining several indexes |
An unindexed filter shows a sequential scan:
EXPLAIN SELECT * FROM orders WHERE status = 'open';Seq Scan on orders (cost=0.00..21846.00 rows=50000 width=33)
Filter: (status = 'open'::text)The word Filter means every row was read and then tested. Index Cond means the index narrowed the rows before they were fetched. A Seq Scan with a Filter that discards most rows is the classic sign of a missing index. EXPLAIN ANALYZE shows this as Rows Removed by Filter: 950000.
A moderately selective index lookup often uses a bitmap scan:
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;Bitmap Heap Scan on orders (cost=5.30..390.12 rows=100 width=33)
Recheck Cond: (customer_id = 42)
-> Bitmap Index Scan on orders_customer_id_idx (cost=0.00..5.28 rows=100 width=0)
Index Cond: (customer_id = 42)Here the 100 matching rows are scattered across the table. The bitmap scan visits each table page once instead of jumping back and forth. Seeing a bitmap scan rather than a plain Index Scan does not mean something is wrong.
How to read a plan
Work from the node that consumes the most time, not from the top line. Totals at a parent node include the time of its children.
When the planner ignores your index
A sequential scan next to an existing index is not always a bug. Common causes:
- The predicate matches too many rows. If a query returns, say, a third of the table, reading the whole table in order is cheaper than thousands of random page fetches. Selectivity decides this, as covered earlier.
- The table is small. On a few pages, a scan costs less than traversing an index.
- The predicate is not index-friendly. A function on the column, such as
date_trunc('month', created_at) = ..., hides the column from a plain index. - The leading column of a composite index is missing from the condition.
- Statistics are stale. The planner thinks few rows match when many do, or the reverse.
To test whether an index could help, you can discourage sequential scans for one session:
SET enable_seqscan = off;
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;
RESET enable_seqscan;This does not forbid sequential scans. It adds a large penalty to their cost. If the index plan is then faster in actual time, the planner's cost estimates are off. If it is slower, the planner was right. Use this only for diagnosis, never in application code.
Edge cases to remember
- Timing includes instrumentation overhead. On some systems,
EXPLAIN (ANALYZE, TIMING OFF)gives lower-overhead row counts. - The first run may be slow because pages were not cached. Run the query twice and read
BUFFERSto see whethershared readpages were the cause. - A plan for one parameter value may differ from a plan for another. A query on a customer with 10 orders and one with 500,000 orders can legitimately use different nodes.
- Prepared statements may use a generic plan that ignores the specific value. Plans seen in
EXPLAINwith literal values might not match what your application runs. - Costs are estimates. A lower cost does not guarantee a faster query.
Exercise
You run EXPLAIN ANALYZE on SELECT * FROM orders WHERE status = 'open' and see "Seq Scan on orders ... rows=50000 ... (actual ... rows=50000 loops=1)" with "Rows Removed by Filter: 950000". An index on status exists. Give two reasons the planner may be correct to use the sequential scan, and one check you would run to find out.
Show answer
The condition matches about 5% of rows, scattered across the whole table, so an index scan would need many random page fetches and may cost more than reading the table once in order. Also, if statistics were stale, the planner might misjudge the match count. Check by comparing estimated and actual rows (they match here, so the estimate is fine), then run SET enable_seqscan = off and compare the actual time of the index plan. If the index plan is slower, the sequential scan was the right choice. A partial index on WHERE status = 'open' would be a better fit for this query.