Skip to main content
SQLIterixs

How to read an EXPLAIN: the execution plan in PostgreSQL, MySQL and SQL Server

Your query takes seconds and you don't know why. EXPLAIN shows what the database does inside: whether it scans the whole table, which index it uses and how many rows it expects.

A shop's orders screen takes three seconds to load one customer's orders. The query is short: SELECT id, total FROM orders WHERE customer_id = 7. Before adding a random index or rewriting it, ask the database how it plans to run it. That's what EXPLAIN does.

EXPLAIN doesn't change your data. Put in front of a query, it returns its execution plan: the steps the engine chose, in which order and how much it thinks each will cost. The short definition is in the glossary.

See it work in two minutes

This program uses SQLite, which ships with Python, so it runs as is. It creates a table of 10,000 orders, asks for the query plan, creates an index and asks again:

python
import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, total REAL)")
con.executemany(
    "INSERT INTO orders (customer_id, total) VALUES (?, ?)",
    [(i % 500, i * 1.5) for i in range(10_000)],
)

query = "SELECT id, total FROM orders WHERE customer_id = 7"

def plan():
    return [row[3] for row in con.execute("EXPLAIN QUERY PLAN " + query)]

print(plan())
con.execute("CREATE INDEX idx_orders_customer ON orders (customer_id)")
print(plan())
['SCAN orders']
['SEARCH orders USING INDEX idx_orders_customer (customer_id=?)']

Before the index, the plan says SCAN: the database reads all 10,000 rows to keep the 20 belonging to customer 7. Afterwards it says SEARCH ... USING INDEX and jumps straight to those rows. Same query, different path. In SQLite the statement is called EXPLAIN QUERY PLAN; the exact wording can vary slightly between versions.

Same query, different path
Same query, different pathSELECT id, total FROM orders WHERE customer_id = 7SCAN ordersreads all 10,000 rowskeeps 20CREATE INDEX idx_orders_customer ON orders (customer_id)SEARCH orders USING INDEX idx_orders_customer (customer_id=?)customer_id…678…jumps straight to customer 7's 20 rows

PostgreSQL: Seq Scan, Index Scan and cost

In PostgreSQL you write EXPLAIN before the query. With the same table and no index you'd see something like:

sql
EXPLAIN SELECT id, total FROM orders WHERE customer_id = 7;
Seq Scan on orders  (cost=0.00..180.00 rows=20 width=12)
  Filter: (customer_id = 7)

Read it like this:

  • Seq Scan is a sequential scan: the whole table, row by row. With a useful index you'd see Index Scan or Bitmap Heap Scan.
  • cost=0.00..180.00 are the planner's internal units, not milliseconds. The first number is the cost to return the first row; the second, to finish. Use them to compare plans on the same database, not to measure time.
  • rows=20 is how many rows that step is estimated to return.

The exact numbers depend on your data and settings. What matters is the kind of scan and the row estimate.

EXPLAIN ANALYZE: estimated vs actual

EXPLAIN only shows the plan. EXPLAIN ANALYZE runs the query and adds real timings and row counts to each step:

sql
EXPLAIN ANALYZE SELECT id, total FROM orders WHERE customer_id = 7;

Next to each step the output shows something like actual time=0.02..1.10 rows=20 loops=1. Compare the estimated rows with the actual rows: if the database expected 20 rows and got 9,000, its statistics are stale and it may be choosing a bad plan. In PostgreSQL, ANALYZE orders; refreshes those statistics.

Careful: because it really runs the statement, EXPLAIN ANALYZE on an UPDATE or DELETE changes your data. To measure a write, do it inside a transaction that ends with ROLLBACK.

MySQL: look at type, key and rows

MySQL also uses EXPLAIN SELECT ..., but returns a table instead of a tree. Focus on three columns:

ColumnWhat it tells you
typeHow it accesses the table. ALL is a full scan; ref or range use an index.
keyThe index it chose, or NULL if none.
rowsHow many rows it expects to examine.

A row with type = ALL, key = NULL and rows close to the table size is MySQL's version of a Seq Scan. Since MySQL 8.0.18 there is also EXPLAIN ANALYZE, which runs the query and shows real timings.

SQL Server: the graphical plan

In SQL Server Management Studio, Ctrl+L shows the estimated plan without running the query, and Ctrl+M turns on the actual plan for the next run. Look for a Table Scan or Clustered Index Scan over a large table where you expected an Index Seek, and for the operator with the highest cost percentage. In code, SET SHOWPLAN_TEXT ON returns the estimated plan as text.

What to check first in any engine

  1. Full scans over large tables with a filter that returns few rows: they usually call for an index on the WHERE or JOIN column.
  2. Estimates far from reality in EXPLAIN ANALYZE: refresh statistics before touching the query.
  3. The most expensive step: optimize that one, not the one that catches your eye.

A full scan isn't always a mistake. On a small table, or when the query returns a large share of the rows, reading it all is faster than bouncing through an index. That's why the planner sometimes ignores an index you just created.

Practice with your own queries

Change one thing at a time and ask for the plan again. In the example above, try WHERE total > 100 with the index in place: the plan goes back to SCAN, because the index is on customer_id, not total. You can practice queries in the online SQL editor, review what an index is and keep the SQL cheat sheet nearby. To go deeper, the official PostgreSQL EXPLAIN docs are among the clearest.

Share

LinkedIn