Before continuing: This entry is part of the indexes guide. If you are new to the topic, start with INDEX.
EXPLAIN example
We want to list the products that are in stock, from the most stock to the least:
SELECT id, name, stock
FROM products
WHERE stock > 0
ORDER BY stock DESC;In SQLite we can put this in front of it: EXPLAIN QUERY PLAN:
EXPLAIN QUERY PLAN
SELECT id, name, stock
FROM products
WHERE stock > 0
ORDER BY stock DESC;How to use EXPLAIN
The name and format vary between engines. PostgreSQL offers options such as ANALYZE, which runs the statement and adds real measurements. SQLite separates EXPLAIN, which is low-level, and EXPLAIN QUERY PLAN, which gives a higher-level description.
Differences and trade-offs
An estimated plan describes the intended strategy. In PostgreSQL, EXPLAIN ANALYZE runs the statement and shows the times and rows observed. That difference matters: an estimate can be far from reality.
Running ANALYZE on a write without care
EXPLAIN ANALYZE
DELETE FROM orders
WHERE status = 'cancelled';In PostgreSQL, EXPLAIN ANALYZE runs the statement. With INSERT, UPDATE or DELETE it can change data. Use a transaction you can roll back, or work in a safe environment.
Key differences between engines
Plans, operation names and costs cannot be compared directly between PostgreSQL, SQLite, MySQL, SQL Server and Oracle. Even the format can change between versions. Learn to recognise the ideas (reading a table, index access, sorting and joining) and check the documentation for your particular engine.
Read the plan with a question and a measurement
Start with the operation you want to explain: finding a few rows, scanning a table to summarise it or producing sorted output. In SQLite, SCAN describes a scan and SEARCH access to a subset through a condition. A full scan does not prove there is a problem: it can be reasonable for a small table or for a query that needs almost all its rows.
In the example, the stock filter and the sort compete to shape the access. Check whether a temporary structure appears for sorting and which index the read uses. Do not add an index just because the plan mentions the table. An index also costs space and work on writes; measure the query with data whose volume and distribution resemble production, as well as reviewing the plan.
Compare one change at a time, keeping the same query and test data. Record the time, the number of rows and the result, because a faster rewrite that returns different products is not an equivalent improvement. The text of EXPLAIN QUERY PLAN may change between versions and should not be treated as a contract for an application. In PostgreSQL, the observed and estimated rows from EXPLAIN ANALYZE help locate estimation errors, but that option actually executes the statement.
Technical questions: SQLite: how to interpret EXPLAIN QUERY PLAN (opens in a new tab).