Sub topic 1
What EXPLAIN shows and why it matters
A slow query is hard to fix if you only know that it is slow. You need to know what the database actually does to run it. In PostgreSQL, EXPLAIN shows you that. This chapter covers what EXPLAIN prints, where it fits in the life of a query, and how to use it as your first diagnostic step. Later chapters go into each part of the output.
Prerequisites
This chapter assumes you can do the following:
- Write
SELECTqueries withWHERE,JOIN,GROUP BYandORDER BY. - Explain in a sentence what a database index is: a separate structure that lets the database find rows without reading the whole table.
- Run SQL in
psqlor another client, and read its text output.
The examples use PostgreSQL and a small shop schema with customers and orders tables. Other databases have an equivalent command, and the last chapter of this tutorial compares them.
What EXPLAIN does
SQL says what result you want, not how to compute it. The database must choose how: which indexes to use, which table to read first, and which algorithm to use for each join. The part of PostgreSQL that makes these choices is the planner (also called the optimizer). Its output is a query plan, a recipe the executor follows.
EXPLAIN prints that plan. The statement you give it is not run, so it returns quickly even if the query itself would take an hour.
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;On a table with no index on customer_id, the output looks like this:
QUERY PLAN
-----------------------------------------------------------
Seq Scan on orders (cost=0.00..1834.00 rows=5 width=44)
Filter: (customer_id = 42)The exact numbers depend on your data. The structure is always the same. Each plan node has a name (Seq Scan on orders), a parenthesized group of estimates, and indented detail lines such as Filter.
Where the planner fits
A query passes through several stages. EXPLAIN shows the result of the planning stage and stops before execution.
The planner works from statistics, which are summaries of your data that PostgreSQL collects, such as how many rows a table has and how common each value is. The plan is therefore only as good as those statistics. Two consequences follow:
- The same query can get different plans as the table grows or its data distribution changes.
- A plan that looks wrong is often the result of wrong estimates, not a planner bug.
What each part of a node means
Look again at the node Seq Scan on orders (cost=0.00..1834.00 rows=5 width=44).
| Part | Meaning |
|---|---|
| `Seq Scan on orders` | The operation (a sequential scan, which reads the whole table) and its target. |
| `cost=0.00..1834.00` | The planner's estimate of effort: startup cost, then total cost. |
| `rows=5` | The estimated number of rows this node returns. |
| `width=44` | The estimated average size of each returned row, in bytes. |
| `Filter: ...` | A condition checked against each row the node reads. |
Cost is measured in arbitrary units, not milliseconds. By default, reading one page sequentially costs 1.0, and everything else is scaled relative to that. Use costs to compare alternative plans for the same query, not to predict run time. The next chapters cover cost, rows and width in detail.
Reading the plan as a tree
A plan is a tree. Indentation shows nesting. A child node feeds rows to its parent, and the root at the top produces the final result. Lines beginning with -> mark child nodes.
EXPLAIN
SELECT c.name, count(*) AS order_count
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.name;A plan for this query might look like:
HashAggregate (cost=2450.10..2460.10 rows=1000 width=40)
Group Key: c.name
-> Hash Join (cost=30.50..2200.00 rows=50000 width=32)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (cost=0.00..1500.00 rows=50000 width=4)
-> Hash (cost=18.00..18.00 rows=1000 width=36)
-> Seq Scan on customers c (cost=0.00..18.00 rows=1000 width=36)Execution works from the innermost nodes outward. Both Seq Scan nodes read their tables first. The Hash node builds a lookup table from customers. Hash Join matches the order rows against it, and HashAggregate at the root groups the matches. The next chapter walks through this reading order step by step.
EXPLAIN ANALYZE: estimates versus reality
Plain EXPLAIN only shows what the planner expects. To see what really happens, add ANALYZE. This executes the query and reports measured values next to the estimates.
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, count(*) AS order_count
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= DATE '2026-01-01'
GROUP BY c.name
ORDER BY order_count DESC
LIMIT 10;Each node now carries an extra group such as (actual time=0.020..8.412 rows=4821 loops=1), giving real time in milliseconds, real row counts, and how many times the node ran. The BUFFERS option adds counts of data pages read from cache and from disk. A large gap between rows= in the estimate and rows= in the actual group is one of the most useful signals in a plan. Chapters later in this tutorial show how to act on it.
To inspect a data-modifying statement without keeping its effects, wrap it in a transaction and roll back:
BEGIN;
EXPLAIN (ANALYZE)
UPDATE orders
SET status = 'archived'
WHERE created_at < DATE '2020-01-01';
ROLLBACK;The rollback undoes the row changes. It does not undo side effects outside the transaction, such as a trigger that calls an external system, or sequence values that were consumed. The chapter on safe use of ANALYZE covers these limits.
Why this matters
When a query is slow, there are many possible causes: a missing index, outdated statistics, a bad join order, a large sort that spills to disk, or simply too much data. Guessing and adding indexes at random wastes time and slows down writes. EXPLAIN replaces guessing with evidence. It lets you:
- See whether an index is used, and if not, check whether the planner's choice was reasonable.
- Find the node where most of the time or I/O goes.
- Detect misestimates that lead the planner to a poor strategy.
- Check a fix, by running
EXPLAINagain after the change and comparing plans.
That last step is a loop you will repeat often:
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE orders;
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;Here ANALYZE orders is the standalone command that refreshes statistics. It is a different thing from the ANALYZE option of EXPLAIN, and the shared name is a common source of confusion. If the planner now picks an index-based scan, the change worked. If it still scans the whole table, you have a new question to investigate, such as whether the filter matches enough of the table that a full scan really is cheaper.
Common mistakes
- Treating cost as time. A cost of 1834 does not mean 1834 ms. Compare costs only between plans of the same query on the same database.
- Trusting a plan from a tiny test table. With few rows, the planner may prefer a sequential scan even when an index exists, because reading a handful of pages is cheaper than using the index. Test on data of realistic size and distribution.
- Forgetting that plain
EXPLAINhas no timings. It shows no run time at all. UseEXPLAIN ANALYZEwhen you need measurements. - Running
EXPLAIN ANALYZEon writes without a transaction. The change is committed unless you roll back. - Reading only the top line. The root's total cost includes everything beneath it. The problem is usually in a node several levels down.
What comes next
The following chapters take the pieces introduced here one at a time: reading the tree, interpreting cost and row estimates, the scan and join node types, and then the actual-versus-estimated comparison that drives most tuning decisions.
Exercise
You run EXPLAIN SELECT * FROM orders WHERE customer_id = 42; and the plan shows Seq Scan on orders (cost=0.00..1834.00 rows=5 width=44). A colleague says the query "takes 1834 milliseconds". Is that correct? What would you run to learn the real run time, and what precaution would you take if the statement were an UPDATE?
Show answer
No. Cost is in arbitrary planner units, not milliseconds, and plain EXPLAIN does not execute the query, so it reports no timings. Run EXPLAIN (ANALYZE) to execute the query and see actual time, rows and loops. For an UPDATE, wrap it in BEGIN; ... ROLLBACK; so the changes do not persist.
Exercise
In this plan, which node runs first, and which produces the final result? HashAggregate -> Hash Join -> Seq Scan on orders o -> Hash -> Seq Scan on customers c
Show answer
The innermost nodes run first: the two Seq Scan nodes read their tables, and the Hash node builds a lookup table from customers. Rows flow upward through Hash Join to the root, HashAggregate, which produces the final result.