SQLite Indexes and Query Planner Cheatsheet

CREATE INDEX patterns, covering and partial indexes, EXPLAIN QUERY PLAN, ANALYZE, and practical tuning tips for SQLite queries.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Create and use indexes
Create a basic index
CREATE INDEX idx_posts_user_id ON posts(user_id);

# Index a frequently filtered column.

Create a composite index
CREATE INDEX idx_posts_user_created_at ON posts(user_id, created_at DESC);

# Index multiple columns in query order.

Create a unique index
CREATE UNIQUE INDEX idx_users_email ON users(email);

# Enforce uniqueness and speed up lookups.

Create a partial index
CREATE INDEX idx_sessions_active ON sessions(user_id)
WHERE revoked_at IS NULL;

# Index only rows that match a predicate.

## Inspect query plans
Explain a query plan
EXPLAIN QUERY PLAN
SELECT * FROM posts WHERE user_id = 42 ORDER BY created_at DESC LIMIT 10;

# See whether SQLite scans or uses an index.

Enable automatic EXPLAIN QUERY PLAN in shell
.eqp on

# Show plans before each entered statement.

Collect statistics with ANALYZE
ANALYZE;

# Help the planner choose better indexes.

Rebuild indexes
REINDEX;

# Recreate indexes when needed.

Run PRAGMA optimize
PRAGMA optimize;

# Let SQLite perform lightweight maintenance.

Recommended next

No recommendations yet.