Transactions, concurrency and queries · 5 MIN READ

Read EXPLAIN QUERY PLAN: SCAN, SEARCH, covering indexes, sorts and ANALYZE

Read EXPLAIN QUERY PLAN output from Go, add indexes that turn scans into searches and remove temporary sorts, use expression indexes for computed filters, and keep statistics fresh with ANALYZE and PRAGMA optimize.

An SQLite query that is fast on a hundred rows can scan the whole table on a million. EXPLAIN QUERY PLAN tells you how the planner will run a statement before you discover it in production: whether it scans or searches, which index it uses, whether it can answer from the index alone, and whether it needs a temporary B-tree to sort. Reading it takes a few minutes to learn and pays off on every query you write.

sqlite · A MAP OF THE IDEA

  1. EXPLAIN QUERY PLAN
  2. Find SCAN and TEMP B-TREE
  3. Index equality then order
  4. PRAGMA optimize

Useful when

  • Plans are cheap to read and catch slow queries before production.
  • Covering indexes answer queries without touching the table.

Watch out

  • Every index slows writes and takes space.
  • Plan wording changes between SQLite versions.

Implementation & operation cost: A few minutes per query and representative data; indexes add write and storage cost.

01

The words in a plan

EXPLAIN QUERY PLAN returns rows with id, parent, an unused column and a detail text; the detail is what you read. SCAN table means every row is visited. SEARCH table USING INDEX name (col=?) means the index narrows the rows first. COVERING INDEX means every column the query needs is in the index, so the table itself is never read. USE TEMP B-TREE FOR ORDER BY or GROUP BY means SQLite must sort the results itself. The exact wording can change between SQLite versions, so tests should not assert full plan strings unless the library version is pinned, as it is here.

02

From scans to searches

The program fills a file database with 200 customers and 5000 orders in one transaction, then prints the plan of the same queries before and after adding indexes. It also tries a filter on lower(email), adds an expression index for it, runs ANALYZE and reads sqlite_stat1, and finishes with PRAGMA optimize. The plan helper joins every detail row so multi-step plans fit on one line.

go
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	_ "modernc.org/sqlite"
)

// plan returns the detail column of every EXPLAIN QUERY PLAN row.
func plan(ctx context.Context, db *sql.DB, query string) string {
	rows, err := db.QueryContext(ctx, "EXPLAIN QUERY PLAN "+query)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	var steps []string
	for rows.Next() {
		var id, parent, unused int
		var detail string
		if err := rows.Scan(&id, &parent, &unused, &detail); err != nil {
			log.Fatal(err)
		}
		steps = append(steps, detail)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	return strings.Join(steps, " | ")
}

func exec(ctx context.Context, db *sql.DB, query string, args ...any) {
	if _, err := db.ExecContext(ctx, query, args...); err != nil {
		log.Fatal(err)
	}
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "plans")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	db, err := sql.Open("sqlite", filepath.Join(dir, "shop.db"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	exec(ctx, db, `CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL);
		CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, placed TEXT NOT NULL, total INTEGER NOT NULL)`)
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	for c := 1; c <= 200; c++ {
		if _, err := tx.ExecContext(ctx, "INSERT INTO customers VALUES (?, ?)", c, fmt.Sprintf("User%d@Example.com", c)); err != nil {
			log.Fatal(err)
		}
	}
	for o := 1; o <= 5000; o++ {
		if _, err := tx.ExecContext(ctx, "INSERT INTO orders (customer_id, placed, total) VALUES (?, ?, ?)",
			o%200+1, fmt.Sprintf("2026-%02d-%02d", o%12+1, o%28+1), o%97*10); err != nil {
			log.Fatal(err)
		}
	}
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}

	byCustomer := "SELECT id, total FROM orders WHERE customer_id = 42"
	fmt.Println("1 no index:       ", plan(ctx, db, byCustomer))
	exec(ctx, db, "CREATE INDEX orders_customer ON orders (customer_id)")
	fmt.Println("2 with index:     ", plan(ctx, db, byCustomer))
	fmt.Println("3 index only:     ", plan(ctx, db, "SELECT count(*) FROM orders WHERE customer_id = 42"))

	recent := "SELECT id, placed FROM orders WHERE customer_id = 42 ORDER BY placed DESC LIMIT 5"
	fmt.Println("4 sort needed:    ", plan(ctx, db, recent))
	exec(ctx, db, "CREATE INDEX orders_customer_placed ON orders (customer_id, placed)")
	fmt.Println("5 sorted by index:", plan(ctx, db, recent))

	exec(ctx, db, "CREATE INDEX customers_email ON customers (email)")
	byEmail := "SELECT id FROM customers WHERE lower(email) = 'user7@example.com'"
	fmt.Println("6 lower(email):   ", plan(ctx, db, byEmail))
	exec(ctx, db, "CREATE INDEX customers_email_lower ON customers (lower(email))")
	fmt.Println("7 expression idx: ", plan(ctx, db, byEmail))

	var id int
	if err := db.QueryRowContext(ctx, byEmail).Scan(&id); err != nil {
		log.Fatal(err)
	}
	fmt.Println("found customer", id)

	exec(ctx, db, "ANALYZE")
	rows, err := db.QueryContext(ctx, "SELECT idx, stat FROM sqlite_stat1 WHERE tbl = 'orders' ORDER BY idx")
	if err != nil {
		log.Fatal(err)
	}
	for rows.Next() {
		var idx, stat string
		if err := rows.Scan(&idx, &stat); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("sqlite_stat1 %s: %s\n", idx, stat)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	rows.Close()
	fmt.Println("8 after ANALYZE:  ", plan(ctx, db, byCustomer))
	exec(ctx, db, "PRAGMA optimize")
	fmt.Println("PRAGMA optimize ran")
}
Read the code

Without an index the lookup is SCAN orders. After orders_customer it is a SEARCH on customer_id=?, and count(*) uses the COVERING INDEX. Ordering by placed adds USE TEMP B-TREE FOR ORDER BY until the index on (customer_id, placed) serves both the filter and the order. lower(email) scans customers despite the email index; the expression index turns it into a search. ANALYZE records 5000 rows and about 25 per customer.

03

Design indexes for the query, left to right

A composite index is sorted by its first column, then the second, and so on. Equality columns go first, then the column used for range or ORDER BY, so (customer_id, placed) serves WHERE customer_id = ? ORDER BY placed DESC without a sort; SQLite can walk an index backwards for DESC. Every index entry also carries the rowid, which is why that query became covering: it needed only id and placed. Each index costs space and slows every insert, update and delete on the table, so add the ones your real queries need and drop indexes that a wider one already covers, such as orders_customer once the composite exists.

04

Functions on columns and expression indexes

An index on email stores the values as written; lower(email) = ? asks about different values, so the planner cannot use it and scans. Either store a normalised column, declare the column with COLLATE NOCASE and compare without the function, or create an index on the exact expression, which SQLite has supported since 3.9. The query must use the same expression as the index for the planner to match it. The same rule applies to date(created) or substr(code, 1, 3): wrap the column in a function and the plain index no longer helps.

sql
CREATE INDEX customers_email_lower ON customers (lower(email));
SELECT id FROM customers WHERE lower(email) = ?; -- SEARCH ... (<expr>=?)

-- or normalise on write and compare the column directly
CREATE TABLE accounts (email TEXT NOT NULL COLLATE NOCASE UNIQUE);
Read the code

The expression index stores lower(email) for each row, so a query using the same expression becomes a SEARCH. A NOCASE column compares case-insensitively for ASCII letters and its UNIQUE index enforces that rule too.

05

ANALYZE, sqlite_stat1 and PRAGMA optimize

ANALYZE reads each index and stores the results in sqlite_stat1: the row count, then the average number of rows per distinct prefix of the index, which is how 5000 25 says about 25 orders per customer. The planner uses those numbers to choose between indexes when more than one could apply. PRAGMA optimize analyses only what looks stale and is usually quick. The SQLite documentation recommends running it just before closing each short-lived connection; for long-lived connections, run PRAGMA optimize=0x10002 when the connection opens and PRAGMA optimize periodically, for example daily; and always after schema changes, especially CREATE INDEX. Check plans again after adding data in bulk.

06

Make plans part of review

For each query that runs on a request path, run EXPLAIN QUERY PLAN against a database with realistic data and look for SCAN on large tables and TEMP B-TREE on hot paths. A small Go test can assert that critical queries do not SCAN, as long as it pins the SQLite library version through go.mod. Measure with real sizes before adding indexes for everything, and remember that a SCAN of a ten-row lookup table is perfectly fine.

TAKE THIS WITH YOU

Read EXPLAIN QUERY PLAN for every hot query: turn SCAN into SEARCH with indexes ordered equality first, remove TEMP B-TREE sorts with the right composite index, match function filters with expression indexes and keep statistics current with PRAGMA optimize.

Check your understanding

customers has an index on email, yet WHERE lower(email) = ? shows SCAN customers. What fixes it?

Go to the source

Progress stays in this browser. No account needed.