Lesson 2 of 9 · 24m
Indexes and the Query Planner: Small Engine, Real Optimizer
How SQLite chooses access paths, why ANALYZE matters, how covering indexes work, and the schema habits that keep queries predictable.
SQLite's query planner is small but real. It estimates costs, chooses join orders, uses indexes, and sometimes picks a plan you did not expect. The difference between a fast embedded database and a mysterious one is usually whether you inspect plans instead of guessing.
Read the plan before changing the schema
EXPLAIN QUERY PLAN
SELECT id, email FROM users WHERE email = 'ops@example.com';Typical output:
SEARCH users USING INDEX idx_users_email (email=?)SCAN users means a full table walk. On a 300-row settings table, fine. On a 40-million-row event table, it is the incident. Compare the plan to the query shape and table cardinality before touching the schema.
Composite indexes are positional
An index on (tenant_id, created_at, id) serves predicates from left to right:
CREATE INDEX idx_events_tenant_time
ON events (tenant_id, created_at, id);
SELECT id FROM events
WHERE tenant_id = 42 AND created_at >= '2026-01-01'
ORDER BY created_at DESC, id DESC LIMIT 100;The same index barely helps WHERE created_at > ? alone because tenant_id comes first. The leftmost-prefix rule also determines write amplification: every row insert must maintain every index.
ANALYZE gives the planner statistics
SQLite does not know your data distribution unless statistics exist:
ANALYZE;Run it after major bulk loads, migrations that reshape data, or suspicious plan changes. It stores cardinality hints in sqlite_stat1. On very small embedded apps it may matter little; in analytical SQLite databases it can change join order and index choice dramatically.
Covering indexes avoid table lookups
If an index contains every column a query needs, SQLite answers from the index alone:
CREATE INDEX idx_posts_feed_covering
ON posts (blog_id, published_at, id, title, slug);Look for USING COVERING INDEX in the plan. Covering indexes trade storage and write cost for read latency. Partial indexes are another sharp tool: CREATE INDEX ... WHERE finished_at IS NULL indexes only the hot subset, such as open jobs.
Field notes
EXPLAIN QUERY PLANis stable enough for debugging, not a contractual API; capture before/after output during investigations.LIKE 'abc%'can use an index under the right collation;LIKE '%abc'generally cannot.- Every index slows inserts, updates, and
REPLACE; measure write cost on embedded devices, not just read speed. - Expression indexes such as
ON users (lower(email))work only when the query uses a matching expression.
Was this lesson helpful?