Reading EXPLAIN QUERY PLAN output in SQLite

SQLite tells you exactly how it will run a query, if you ask. Here is how to read the answer.

Reading the plan

For staging and small sites we use SQLite. One file is easy to copy, easy to reset, and fast enough for everything we have thrown at it.

EXPLAIN QUERY PLAN
SELECT id, title
FROM posts
WHERE status = 'publish' AND author_id = 42
ORDER BY published_at DESC
LIMIT 10;

-- Before: SCAN posts
-- After:  SEARCH posts USING INDEX idx_posts_author_status (author_id=? AND status=?)
CREATE INDEX idx_posts_author_status ON posts (author_id, status, published_at);

The slow page ran eleven queries, and one of them scanned the whole table on every request. The query plan said so in plain words; we had simply never asked. The snippet above is the whole thing; the version in our repository only adds tests.

Changing schemas safely

  • Read the query plan before adding an index
  • Put the most selective column first
  • Make every migration idempotent
  • Back up before, verify after

Leave a comment

Your email address will not be published. Required fields are marked *