EXPLAIN: read a query plan
Overview
An execution plan describes how the engine intends to obtain a result. Read the nodes and their relationships before deciding whether a query needs tuning. SQLite offers a high-level EXPLAIN QUERY PLAN and a lower-level EXPLAIN instruction listing.
First example
EXPLAIN QUERY PLAN SELECT id FROM ep_order WHERE amount=420;Observed SQLite result (rows in JSON):
[ [ 2, 0, 0, "SEARCH ep_order USING COVERING INDEX ep_amount (amount=?)" ]]How it works
The fixture has 100 orders and an amount index. A plan row has node ID, parent ID, auxiliary value and description. SEARCH means an access path restricts the visited subset; SCAN means a scan strategy, possibly scanning an index. COVERING means the needed values are present in the index. The first example searches for 420; the second intentionally disables ordinary indexes using NOT INDEXED. Both return ID 42 when executed without the prefix. Neither plan establishes elapsed time or number of rows actually visited. PostgreSQL EXPLAIN (FORMAT JSON) produces a structured tree of estimated nodes, with startup/total costs and row estimates. Read children as inputs to parents; execution can be demand-driven and interleaved. Do not equate any scan with a bad plan: scanning can be appropriate for a large fraction of a table.
Practical example
EXPLAIN QUERY PLAN SELECT id FROM ep_order NOT INDEXED WHERE amount=420;Observed SQLite result (rows in JSON):
[ [ 2, 0, 0, "SCAN ep_order" ]]Practice and mistakes
Practice: inspect the plan for amount >= 950 and execute the query ordered by id. Hint 1: change the predicate, not the index. Hint 2: compare the returned IDs 95–100 with a forced scan. Explain why equal results do not prove equal performance.
PostgreSQL 17 example — NOT RUN
BEGIN;SET LOCAL statement_timeout = '10s';SET LOCAL lock_timeout = '2s';CREATE TEMP TABLE ep_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);INSERT INTO ep_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara');CREATE TEMP TABLE ep_order(id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES ep_customer(id), status TEXT NOT NULL CHECK(status IN ('common','rare')), amount INTEGER NOT NULL CHECK(amount>=0));WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM seq WHERE n<100)INSERT INTO ep_order SELECT n, CASE WHEN n<=60 THEN 1 ELSE 2 END, CASE WHEN n<=90 THEN 'common' ELSE 'rare' END,n*10 FROM seq;CREATE INDEX ep_status ON ep_order(status);CREATE INDEX ep_customer_id ON ep_order(customer_id);CREATE INDEX ep_amount ON ep_order(amount);ANALYZE ep_order;
EXPLAIN (FORMAT JSON) SELECT id FROM ep_order WHERE amount=420;ROLLBACK;Expected result, not executed: "Estimated plan tree; no actual rows or timing."