# EXPLAIN & Query Plans

> Read real EXPLAIN output: scan types, cost, rows, Filter and Index Cond, and what EXPLAIN ANALYZE adds, so you can tell why a query is slow.

Subject: SQL | Lesson 41 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/explain-and-query-plans
Previous: [Composite & Partial Indexes](https://codewithanimation.in/sql/composite-and-partial-indexes.md) | Next: [Parameterized Queries & SQL Injection](https://codewithanimation.in/sql/parameterized-queries-and-sql-injection.md)

## EXPLAIN shows the plan before the work

SQL says what you want, not how to get it. The **planner** works out a plan, a tree of steps, and `EXPLAIN` prints it. `EXPLAIN SELECT ...` does not run the query. It only shows the plan the planner chose.

Each line is a **node**. Scan nodes at the bottom read tables: `Seq Scan` reads every row, `Index Scan` walks an index, and `Bitmap Heap Scan` collects row locations from an index first and then reads those pages. Nodes above them, such as `Sort`, work on the rows passed up.

## Guessing is slow, reading the plan is quick

A slow query is slow for a reason you can see in the plan: a Seq Scan over a huge table, a Filter that throws most rows away, a Sort of everything. Reading the plan tells you whether an index would help, before you build one.

## Read cost, rows and width

```
Seq Scan on tenk1  (cost=0.00..445.00 rows=10000 width=244)
```

`cost=0.00..445.00` is `startup..total`. Startup is the work before the first row can come out, total is the work to finish. The units are arbitrary: by default fetching one disk page in sequence costs 1.0, and the planner chooses the plan with the lowest total. `rows` is the planner's estimate of the rows this node passes up, and `width` is the average row size in bytes.

Where does 445 come from? The manual's own sum: 345 pages x 1.0, plus 10000 rows x 0.01 (the default cost of handling a row) = 445.

Now compare the manual's plans for the same table. `WHERE unique1 < 7000` stays a Seq Scan with a `Filter` line, cost 470, because most rows match. `WHERE unique1 < 100` switches to a bitmap scan using the index, cost about 225. `WHERE unique1 = 42` becomes a plain `Index Scan`, cost about 8. The more selective the query, the more the index pays off.

## Common mistake: ANALYZE runs the query, and estimates can be wrong

`EXPLAIN ANALYZE` actually executes the query and adds what really happened: `actual time` in milliseconds, the real `rows`, how many `loops`, and `Rows Removed by Filter`. Because it really runs the query, any side effects happen. To try `EXPLAIN ANALYZE` on an `UPDATE` or `DELETE` without keeping the change, wrap it in `BEGIN` and `ROLLBACK`. It also adds timing overhead, so it can be slower than the plain query.

The planner chooses from statistics about each table: row counts and how the values are spread. They are updated by `VACUUM` and `ANALYZE` and are always approximate. If the estimated `rows` is far from the actual rows, the plan may be a bad one, and running `ANALYZE` on the table is the first thing to try.

Costs are not milliseconds, and you cannot compare them across different queries. Use them to compare plans for the same query, and use `actual time` to measure real time.

## Tip: Look for the big number and the Filter

Read the plan from the most indented node outwards. Find the node with the largest cost or the biggest gap between estimated and actual rows. A `Seq Scan` with a `Filter` that removes most rows is the classic sign that an index on that column could help.

## Try it: Read six real plans

Go through the queries from the first to the last, and use the Decode chips to highlight each part of the plan. Finish with EXPLAIN ANALYZE.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/explain-and-query-plans

## Check yourself

### Question 1

Does a plain `EXPLAIN SELECT ...` (without ANALYZE) run the query?

- A. No, it only shows the plan the planner chose
- B. Yes, and it prints the rows
- C. Yes, but it throws the rows away

Correct answer: A

EXPLAIN shows the plan. Adding ANALYZE makes it run the query and show real timings.

- Why not B: EXPLAIN prints the plan, not the rows. Only EXPLAIN ANALYZE runs the statement.
- Why not C: That describes EXPLAIN ANALYZE. Plain EXPLAIN does not execute anything.

### Question 2

A plan shows `Seq Scan on tenk1 ... Filter: (unique1 < 7000)` and `rows=7000`. What does the Filter line tell you?

- A. Every row was read, and the rows that failed the test were thrown away
- B. An index was used to find the matching rows
- C. Exactly 7000 rows exist in the table

Correct answer: A

A Filter is applied to rows the scan has already read. The scan still had to visit all of them.

- Why not B: An index test would be shown as an Index Cond under an Index Scan or Bitmap Index Scan.
- Why not C: rows=7000 is the estimate of rows passed up. The table has 10000 rows.

### Question 3

You want to see how long an `UPDATE` really takes, without changing the data. What do you do?

- A. BEGIN; EXPLAIN ANALYZE UPDATE ...; ROLLBACK;
- B. Run plain EXPLAIN UPDATE ...
- C. Run EXPLAIN ANALYZE UPDATE ... on its own

Correct answer: A

EXPLAIN ANALYZE executes the statement, so the manual suggests wrapping it in a transaction that you roll back.

- Why not B: Plain EXPLAIN never runs the statement, so it shows no real time.
- Why not C: EXPLAIN ANALYZE really executes the UPDATE, and the change would be kept.

## Remember this

- EXPLAIN shows the plan without running the query. EXPLAIN ANALYZE runs it and adds actual times and row counts.
- cost=startup..total is in arbitrary units (one sequential page fetch is 1.0). rows is an estimate, and width is bytes per row.
- A Filter means rows were read and then discarded. An Index Cond means the index did the narrowing.
- Wrap EXPLAIN ANALYZE of an UPDATE or DELETE in BEGIN and ROLLBACK, and run ANALYZE when estimates look wrong.
