Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
CREATE INDEX events_user_created ON events(user_id, created);sql
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;text
QUERY PLAN
SEARCH events USING INDEX events_user_created (user_id=?)sql
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7 AND created > '2026-03-01';text
QUERY PLAN
SEARCH events USING INDEX events_user_created (user_id=? AND created>?)sql
EXPLAIN QUERY PLAN SELECT * FROM events WHERE created > '2026-03-01';text
QUERY PLAN
SCAN eventsThe first two plans search the index; the second uses both columns (user_id=? AND created>?). The third falls back to a scan, because the index offers no shortcut to a range of created values.
The rule of thumb is "equality columns first, then the range column". An index on (created, user_id) would serve the date filter alone, but for "user 7 after 1 March" it would scan every date after 1 March and check users.
SQLite can sometimes use a skip-scan on the second column when the first has very few distinct values and statistics from ANALYZE exist; do not rely on it for design.
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
CREATE INDEX events_user_created ON events(user_id, created);
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7 AND created > '2026-03-01';
EXPLAIN QUERY PLAN SELECT * FROM events WHERE created > '2026-03-01';Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Composite indexes sort by the first column, then the next
- Filters must use a leading prefix of the columns
- Put equality columns before range columns
- A filter on the second column alone usually cannot seek
Common mistakes
- Creating (a, b) and expecting it to serve WHERE b = ?
- Putting the range column first
Follow-ups
- Would you create a second index on created alone?
- How does ORDER BY interact with a composite index?
Tips
- Use the phone-book analogy: last name, then first name