Database Indexes and Performance · Lesson 54 of 112

Database Query Plans (EXPLAIN)

What you will learn

  • Ask the database for its query plan
  • Tell SCAN from SEARCH
  • Recognise the common plan lines
  • Read the plan of a join
  • Follow a short checklist for a slow query

1. What a query plan is

You tell the database what you want; the query planner decides how. The decision, which index to use, which table to read first, whether to sort, is the query plan. You can ask to see it:

  • SQLite: EXPLAIN QUERY PLAN <query>
  • PostgreSQL: EXPLAIN <query> (the PostgreSQL documentation has an EXPLAIN page; the output looks different from SQLite's, and the PostgreSQL course will cover it)

EXPLAIN QUERY PLAN shows the plan without returning the query's rows. (Careful in PostgreSQL: EXPLAIN alone only plans, but EXPLAIN ANALYZE actually runs the statement. Its documentation warns that an INSERT, UPDATE or DELETE really happens, and suggests wrapping it in BEGIN; ... ROLLBACK;.) This lesson uses SQLite on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The cell shows only the readable plan text. Indexes you create live in your browser's copy; Reset data removes them.

2. The common plan lines

EXPLAIN QUERY PLAN SELECT * FROM orders;
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE order_id = 500;
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE ship_city = 'Leeds';
EXPLAIN QUERY PLAN SELECT * FROM orders ORDER BY order_date;
plan
-----------
SCAN orders
(1 row)

plan
-------------------------------------------------
SEARCH orders USING INTEGER PRIMARY KEY (rowid=?)
(1 row)

plan
-----------
SCAN orders
(1 row)

plan
----------------------------
SCAN orders
USE TEMP B-TREE FOR ORDER BY
(2 rows)
EXPLAIN QUERY PLAN SELECT * FROM transactions;
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE txn_id = 500;
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE kind = 'deposit';
EXPLAIN QUERY PLAN SELECT * FROM transactions ORDER BY amount_cents;
plan
-----------------
SCAN transactions
(1 row)

plan
-------------------------------------------------------
SEARCH transactions USING INTEGER PRIMARY KEY (rowid=?)
(1 row)

plan
-----------------
SCAN transactions
(1 row)

plan
----------------------------
SCAN transactions
USE TEMP B-TREE FOR ORDER BY
(2 rows)
EXPLAIN QUERY PLAN SELECT * FROM students;
EXPLAIN QUERY PLAN SELECT * FROM students WHERE student_id = 100;
EXPLAIN QUERY PLAN SELECT * FROM students WHERE guardian_name = 'Amir Khan';
EXPLAIN QUERY PLAN SELECT * FROM students ORDER BY birth_date;
plan
-------------
SCAN students
(1 row)

plan
---------------------------------------------------
SEARCH students USING INTEGER PRIMARY KEY (rowid=?)
(1 row)

plan
-------------
SCAN students
(1 row)

plan
----------------------------
SCAN students
USE TEMP B-TREE FOR ORDER BY
(2 rows)

Note: plan wording can differ slightly between SQLite versions (and a browser may run an older SQLite than the one used to write this course). The ideas, SCAN versus SEARCH and whether an index is used, stay the same.

Plan line Meaning
SCAN table reads every row: fine for small tables or when you want everything, a warning sign for a selective query
SEARCH table USING INDEX name (col=?) jumps to matching rows through an index
SEARCH table USING INTEGER PRIMARY KEY (rowid=?) looks up by the primary key (the row's own id), the fastest lookup
USING COVERING INDEX answered from the index alone (lesson 7.5)
USE TEMP B-TREE FOR ORDER BY had to sort the rows in a temporary structure

The col=? part shows which condition used the index. SCAN table USING INDEX idx means the table is read in index order, which avoids a sort but still reads the whole table.

3. Reading a join

A join has one plan line for each table, in the order the database reads them:

EXPLAIN QUERY PLAN SELECT c.last_name, o.order_date FROM customers c JOIN orders o ON o.customer_id = c.customer_id WHERE c.customer_id = 10;
plan
--------------------------------------------
SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
SCAN o
(2 rows)
EXPLAIN QUERY PLAN SELECT c.full_name, a.balance_cents FROM customers c JOIN accounts a ON a.customer_id = c.customer_id WHERE c.customer_id = 10;
plan
--------------------------------------------
SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
SCAN a
(2 rows)
EXPLAIN QUERY PLAN SELECT t.name, s.room FROM teachers t JOIN sections s ON s.teacher_id = t.teacher_id WHERE t.teacher_id = 10;
plan
--------------------------------------------
SEARCH t USING INTEGER PRIMARY KEY (rowid=?)
SCAN s
(2 rows)

Reading it: first find the row of the first table by its primary key (one row), then look at the second table: SCAN means it reads all of its rows to find the matching ones, because the foreign key column has no index. That is the problem the plan reveals. Add the index and look again:

CREATE INDEX idx_orders_customer ON orders (customer_id);
EXPLAIN QUERY PLAN SELECT c.last_name, o.order_date FROM customers c JOIN orders o ON o.customer_id = c.customer_id WHERE c.customer_id = 10;
plan
--------------------------------------------------------
SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
SEARCH o USING INDEX idx_orders_customer (customer_id=?)
(2 rows)
CREATE INDEX idx_accounts_customer ON accounts (customer_id);
EXPLAIN QUERY PLAN SELECT c.full_name, a.balance_cents FROM customers c JOIN accounts a ON a.customer_id = c.customer_id WHERE c.customer_id = 10;
plan
----------------------------------------------------------
SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
SEARCH a USING INDEX idx_accounts_customer (customer_id=?)
(2 rows)
CREATE INDEX idx_sections_teacher ON sections (teacher_id);
EXPLAIN QUERY PLAN SELECT t.name, s.room FROM teachers t JOIN sections s ON s.teacher_id = t.teacher_id WHERE t.teacher_id = 10;
plan
--------------------------------------------------------
SEARCH t USING INTEGER PRIMARY KEY (rowid=?)
SEARCH s USING INDEX idx_sections_teacher (teacher_id=?)
(2 rows)

Both tables are now searched, not scanned. Foreign key columns (lesson 3.1) are the usual suspects when a join is slow.

4. Why the planner chooses what it chooses

The planner does not guess. It uses statistics: numbers the database keeps about each table and index, such as how many rows there are and how many rows a typical value matches. With them it estimates which plan is cheapest. When the statistics are missing or old, the planner can choose badly. In SQLite the command ANALYZE collects them into a table called sqlite_stat1:

SELECT name FROM sqlite_master WHERE name = 'sqlite_stat1';
ANALYZE;
SELECT tbl, idx, stat FROM sqlite_stat1 WHERE tbl = 'orders';
name
----
(0 rows)

tbl     idx                  stat
------  -------------------  ------
orders  idx_orders_customer  2600 8
(1 row)
SELECT name FROM sqlite_master WHERE name = 'sqlite_stat1';
ANALYZE;
SELECT tbl, idx, stat FROM sqlite_stat1 WHERE tbl = 'accounts';
name
----
(0 rows)

tbl       idx                    stat
--------  ---------------------  -----
accounts  idx_accounts_customer  450 2
(1 row)
SELECT name FROM sqlite_master WHERE name = 'sqlite_stat1';
ANALYZE;
SELECT tbl, idx, stat FROM sqlite_stat1 WHERE tbl = 'sections';
name
----
(0 rows)

tbl       idx                   stat
--------  --------------------  ----
sections  idx_sections_teacher  41 2
(1 row)

Before ANALYZE there was no statistics table. Afterwards the row for the new index has two numbers: the first is the number of rows in the table, the second is how many rows a typical value of the indexed column matches. Most server databases refresh statistics automatically in the background, but after a huge load or a big delete it is worth running the update command of your database by hand (in PostgreSQL it is also called ANALYZE).

Worked example: a checklist for a slow query

  1. Find the slow query and run EXPLAIN QUERY PLAN on it, with realistic data.
  2. Look for SCAN on a big table where you expect to fetch only a few rows.
  3. Look for USE TEMP B-TREE FOR ORDER BY on a big result.
  4. Add an index on the column in the WHERE, JOIN or ORDER BY that causes it.
  5. Read the plan again: is the line now SEARCH ... USING INDEX?
  6. Measure the time before and after. If it did not help, drop the index (lesson 7.3).

Always test on data about as big as the real thing: on ten rows, every plan is fast.

Common mistakes

  • Reading the plan for a tiny test table and concluding all is fine.
  • Assuming SCAN is always bad. It is correct when you read most of the table anyway.
  • Assuming the plan format is the same everywhere. Each database has its own wording and tools.
  • Adding an index without checking the plan afterwards.

Key takeaways

  • The planner chooses how to run a query; EXPLAIN QUERY PLAN (SQLite) shows its choice.
  • SCAN reads every row; SEARCH ... USING INDEX jumps to matching rows.
  • TEMP B-TREE FOR ORDER BY means a separate sort.
  • A join shows one line per table; a SCAN on the second table usually means a missing index on the join column.
  • Check the plan before and after every index change.
  • The planner relies on statistics about the data; refresh them after big changes.

Practice

1. What is the difference between SCAN and SEARCH?

Show answer

SCAN reads every row; SEARCH finds matching rows through an index or primary key.

2. What did SCAN o tell us in the join plan?

Show answer

All orders were read for the customer, because orders.customer_id had no index.

3. After loading a million new rows, the same query suddenly gets a worse plan. Which cause would you check first?

Show answer

Out-of-date statistics. The planner still believes the table is small. Refresh them (ANALYZE) and read the plan again.

4. Which lookup was fastest in the lesson's plans?

Show answer

The primary key lookup (USING INTEGER PRIMARY KEY (rowid=?)).

5. You see USE TEMP B-TREE FOR ORDER BY on a 1,000,000-row result. What could you try?

Show answer

An index on the ORDER BY column(s), then check that the line disappears.

6. Why test with realistic amounts of data?

Show answer

On very small tables every plan is fast, and the planner may also choose differently than it would on large data.