// troubleshooting guide

How to read an execution plan

An execution plan is the list of steps the database took to answer a query. How to get one that includes what really happened, how to read it, and which numbers to look at first.

Covers SQL Server PostgreSQL MySQL SQLite Oracle

The symptom

Every engine can show how it ran a query: which tables it read, in what order, how it joined them and how many rows moved between the steps. There are two kinds of plan. An estimated plan is what the optimizer intends to do, with its guesses for row counts. An actual plan is produced by running the query and adds what happened: real row counts, and on most engines time and pages read per step. Most plan problems are a difference between the two, so get an actual plan whenever the query is safe to run.

Paste either kind into the query plan viewer to see it as a diagram with the costly steps marked. The examples use a shop schema with 20,000 customers, 400,000 orders and 800,000 order items, and the same query on every engine: orders that are still pending, counted by the customer's country.

Diagnose it

PostgreSQL

EXPLAIN alone shows the estimated plan. ANALYZE runs the statement and adds the actual numbers; BUFFERS adds pages read per step. For the viewer, FORMAT JSON carries the same information.

EXPLAIN (ANALYZE, BUFFERS)
SELECT c.country, count(*)
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'pending'
GROUP BY c.country;
Finalize GroupAggregate  (cost=8194.41..8195.92 rows=5 width=11) (actual time=8.715..10.571 rows=1.00 loops=1)
  Group Key: c.country
  Buffers: shared hit=4997
  ->  Gather Merge  (cost=8194.41..8195.81 rows=12 width=11) (actual time=8.711..10.568 rows=3.00 loops=1)
        Workers Planned: 2
        Workers Launched: 2
        Buffers: shared hit=4997
        ->  Sort  (cost=7194.39..7194.40 rows=5 width=11) (actual time=7.460..7.461 rows=1.00 loops=3)
              Sort Key: c.country
              Sort Method: quicksort  Memory: 25kB
              Buffers: shared hit=4997
              Worker 0:  Sort Method: quicksort  Memory: 25kB
              Worker 1:  Sort Method: quicksort  Memory: 25kB
              ->  Partial HashAggregate  (cost=7194.28..7194.33 rows=5 width=11) (actual time=7.449..7.450 rows=1.00 loops=3)
                    Group Key: c.country
                    Batches: 1  Memory Usage: 32kB
                    Buffers: shared hit=4983
                    Worker 0:  Batches: 1  Memory Usage: 32kB
                    Worker 1:  Batches: 1  Memory Usage: 32kB
                    ->  Hash Join  (cost=617.00..7186.45 rows=1567 width=3) (actual time=2.154..7.338 rows=1333.33 loops=3)
                          Hash Cond: (o.customer_id = c.customer_id)
                          Buffers: shared hit=4983
                          ->  Parallel Seq Scan on orders o  (cost=0.00..6565.33 rows=1567 width=4) (actual time=0.006..5.088 rows=1333.33 loops=3)
                                Filter: ((status)::text = 'pending'::text)
                                Rows Removed by Filter: 132000
                                Buffers: shared hit=4482
                          ->  Hash  (cost=367.00..367.00 rows=20000 width=7) (actual time=2.071..2.071 rows=20000.00 loops=3)
                                Buckets: 32768  Batches: 1  Memory Usage: 1038kB
                                Buffers: shared hit=501
                                ->  Seq Scan on customers c  (cost=0.00..367.00 rows=20000 width=7) (actual time=0.006..0.814 rows=20000.00 loops=3)
                                      Buffers: shared hit=501
Planning Time: 0.285 ms
Execution Time: 10.659 ms

Each line has two brackets. The first is the estimate: cost in the planner's own units and rows. The second is what happened: actual time in milliseconds, rows y loops. Time and rows are averages per loop, so multiply by loops to get the total. The scan of orders above ran in three processes and each found a third of the pending orders.

MySQL and MariaDB

MySQL 8.0.18 and later run the statement with EXPLAIN ANALYZE and print a tree with estimates and actual numbers side by side:

EXPLAIN ANALYZE
SELECT c.country, count(*)
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'pending'
GROUP BY c.country;
-> Table scan on <temporary>  (actual time=44.5..44.5 rows=1 loops=1)
    -> Aggregate using temporary table  (actual time=44.5..44.5 rows=1 loops=1)
        -> Nested loop inner join  (cost=54270 rows=39933) (actual time=0.0756..44.1 rows=4000 loops=1)
            -> Filter: (o.`status` = 'pending')  (cost=40294 rows=39933) (actual time=0.07..43.5 rows=4000 loops=1)
                -> Table scan on o  (cost=40294 rows=399330) (actual time=0.0611..30.8 rows=400000 loops=1)
            -> Single-row index lookup on c using PRIMARY (customer_id=o.customer_id)  (cost=0.25 rows=1) (actual time=56.8e-6..71.6e-6 rows=1 loops=4000)

As in PostgreSQL, actual time y rows are per loop. The last line ran 4,000 times, once per pending order. Plain EXPLAIN gives the estimated plan as a table, and EXPLAIN FORMAT=JSON gives it with costs.

MariaDB uses ANALYZE in place of EXPLAIN ANALYZE. In its JSON form the fields that start with r_ are the measured ones, next to the estimates without the prefix. The run below is followed by those fields for the two tables:

ANALYZE FORMAT=JSON
SELECT c.country, count(*)
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'pending'
GROUP BY c.country\G
"table_name": "o",
"access_type": "ALL",
"r_loops": 1,
"rows": 399054,
"r_rows": 400000,
"filtered": 100,
"r_filtered": 1
"table_name": "c",
"access_type": "eq_ref",
"r_loops": 4000,
"rows": 1,
"r_rows": 1,
"filtered": 100,
"r_filtered": 100

SQL Server

SET STATISTICS XML ON runs each statement and returns its actual plan as an extra result set holding one XML document. Save that document as a .sqlplan file or paste it into the viewer.

SET STATISTICS XML ON;
GO
SELECT c.Country, COUNT(*) AS Orders
FROM dbo.Customers AS c
JOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId
WHERE o.Status = 'pending'
GROUP BY c.Country;
GO
SET STATISTICS XML OFF;

SET SHOWPLAN_XML ON returns the estimated plan in the same format without running the statement. SET SHOWPLAN_TEXT ON does the same as plain text, which is easier to read in a terminal:

SET SHOWPLAN_TEXT ON;
GO
SELECT c.Country, COUNT(*) AS Orders
FROM dbo.Customers AS c
JOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId
WHERE o.Status = 'pending'
GROUP BY c.Country;
GO
SET SHOWPLAN_TEXT OFF;
|--Compute Scalar(DEFINE:([Expr1002]=CONVERT_IMPLICIT(int,[Expr1005],0)))
     |--Hash Match(Aggregate, HASH:([c].[Country]), RESIDUAL:([learnfx].[dbo].[Customers].[Country] as [c].[Country] = [learnfx].[dbo].[Customers].[Country] as [c].[Country]) DEFINE:([Expr1005]=COUNT(*)))
          |--Merge Join(Inner Join, MERGE:([c].[CustomerId])=([o].[CustomerId]), RESIDUAL:([learnfx].[dbo].[Customers].[CustomerId] as [c].[CustomerId]=[learnfx].[dbo].[Orders].[CustomerId] as [o].[CustomerId]))
               |--Clustered Index Scan(OBJECT:([learnfx].[dbo].[Customers].[PK__Customer__A4AE64D854FCACE0] AS [c]), ORDERED FORWARD)
               |--Sort(ORDER BY:([o].[CustomerId] ASC))
                    |--Clustered Index Scan(OBJECT:([learnfx].[dbo].[Orders].[PK__Orders__C3905BCFF902724C] AS [o]), WHERE:([learnfx].[dbo].[Orders].[Status] as [o].[Status]='pending'))

Oracle

EXPLAIN PLAN gives an estimated plan. For actual numbers, run the statement with the GATHER_PLAN_STATISTICS hint and then ask for the plan of the last statement in the session. In SQL*Plus turn SERVEROUTPUT off first, or the last statement is not the one you ran.

SET SERVEROUTPUT OFF

SELECT /*+ GATHER_PLAN_STATISTICS */ c.country, count(*)
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'pending'
GROUP BY c.country;

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(FORMAT => 'ALLSTATS LAST'));
| Id  | Operation           | Name      | Starts | E-Rows | A-Rows |   A-Time   | Buffers |  OMem |  1Mem | Used-Mem |
|   0 | SELECT STATEMENT    |           |      1 |        |      1 |00:00:00.01 |    2512 |       |       |          |
|   1 |  HASH GROUP BY      |           |      1 |      5 |      1 |00:00:00.01 |    2512 |  1161K|  1161K|          |
|*  2 |   HASH JOIN         |           |      1 |   4000 |   4000 |00:00:00.01 |    2512 |  2278K|  2278K|  878K (0)|
|*  3 |    TABLE ACCESS FULL| ORDERS    |      1 |   4000 |   4000 |00:00:00.01 |    2391 |       |       |          |
|   4 |    TABLE ACCESS FULL| CUSTOMERS |      1 |  20000 |  20000 |00:00:00.01 |     121 |       |       |          |

E-Rows is the estimate and A-Rows the actual row count. Starts is how many times the step ran, A-Time the time spent in the step and everything under it, and Buffers the blocks read.

SQLite

EXPLAIN QUERY PLAN shows the plan without running the query. It has no row counts or timings; what matters is whether each table is read with SCAN (all of it) or SEARCH (through an index or the primary key).

EXPLAIN QUERY PLAN
SELECT c.country, count(*)
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'pending'
GROUP BY c.country;
|--SCAN o
|--SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
`--USE TEMP B-TREE FOR GROUP BY

The order to read it in

A plan is a tree. The steps indented furthest run first and feed their rows to the step above them, and the top line produces the result. In the PostgreSQL plan above, the scans of orders y customers are the leaves, the hash join combines them, and the aggregates on top count the joined rows. When two steps sit under a join, the engine decides which side drives the other; join algorithms explains how each kind of join uses its two inputs.

Times and costs are cumulative: the number on a step includes everything beneath it. To find what a step cost by itself, subtract its children. The operator reference lists what each kind of step does.

Fix it

Find the step where the time goes

With an actual plan, walk down from the top and follow the largest time until a step's own time is much larger than its children's. That step, or the rows it was given, is the problem. The usual findings, each with its own guide:

Compare estimated rows with actual rows

Next to every actual row count is the optimizer's estimate. When they differ by a factor of ten or more, the optimizer chose the rest of the plan for a different amount of data than it got: the wrong join type, the wrong join order, too little memory. Find the lowest step in the tree where the two numbers part ways; the cause is there, and everything above inherits it. Row estimates that are far off covers the causes and fixes.

When to leave it alone

A scan is not a fault by itself, and neither is a sort or a hash join. A plan is good when the work it does is in proportion to the rows it returns. If the query is fast enough, runs rarely, and its estimates match what happened, there is nothing to fix.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Capture an actual plan, not only an estimated one, when the query is safe to run.
  2. Read from the most indented steps up to the top line.
  3. Multiply per-loop rows and time by the loop count.
  4. Follow the largest time down the tree to the step that owns it.
  5. Compare estimated and actual rows at every step; start with the lowest step where they differ.
  6. Open the plan in the plan viewer to see the costly steps marked.

Questions that come up

What is the difference between an estimated and an actual execution plan?

An estimated plan is what the optimizer intends to do, with predicted row counts, and is produced without running the query. An actual plan comes from running the query and adds the real row counts, and on most engines the time and pages read per step.

Does EXPLAIN ANALYZE run the query?

Yes. In PostgreSQL and MySQL, EXPLAIN ANALYZE executes the statement and discards the result rows. For an INSERT, UPDATE or DELETE the changes are made, so wrap it in a transaction and roll back if you do not want them kept.

In what order do I read an execution plan?

Start at the most indented steps, which read the tables, and work up to the top line, which returns the result. Each step passes its rows to the step above it.

What does cost mean in an execution plan?

Cost is the optimizer's estimate of work in its own units, used to compare alternative plans for the same query. It is not a time. Use the actual time and row counts to judge how the query ran.

How do I get an actual execution plan in SQL Server?

Run SET STATISTICS XML ON before the statement. SQL Server executes it and returns the plan with run-time counts as an XML document in an extra result set. In Management Studio the Include Actual Execution Plan button does the same.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.