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 ev_created ON events(created);sql
EXPLAIN QUERY PLAN SELECT COUNT(*) FROM events WHERE substr(created, 1, 7) = '2026-02';text
QUERY PLAN
SCAN events USING COVERING INDEX ev_createdThe plan is a SCAN. SQLite does read the index, because it covers COUNT(*), but it reads every entry and evaluates substr on each one. Rewritten as a half-open range, the plan becomes a SEARCH that touches only February:
sql
EXPLAIN QUERY PLAN SELECT COUNT(*) FROM events WHERE created >= '2026-02-01' AND created < '2026-03-01';text
QUERY PLAN
SEARCH events USING COVERING INDEX ev_created (created>? AND created<?)Other common non-sargable shapes:
WHERE amount + 10 > 50(writeamount > 40)WHERE lower(email) = ?(use an expression index, or store normalized values)WHERE date(created) = ?on timestamps (use a range)
Both versions return the same rows here; only the work differs.
sql
SELECT (SELECT COUNT(*) FROM events WHERE substr(created, 1, 7) = '2026-02') AS by_substr,
(SELECT COUNT(*) FROM events WHERE created >= '2026-02-01' AND created < '2026-03-01') AS by_range;| by_substr | by_range |
|---|---|
| 616 | 616 |
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 ev_created ON events(created);
EXPLAIN QUERY PLAN SELECT COUNT(*) FROM events WHERE substr(created, 1, 7) = '2026-02';
EXPLAIN QUERY PLAN SELECT COUNT(*) FROM events WHERE created >= '2026-02-01' AND created < '2026-03-01';
SELECT (SELECT COUNT(*) FROM events WHERE substr(created, 1, 7) = '2026-02') AS by_substr,
(SELECT COUNT(*) FROM events WHERE created >= '2026-02-01' AND created < '2026-03-01') AS by_range;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Functions on an indexed column usually block index use
- Rewrite as a range on the bare column
- Sargable means the predicate can use an index
- Expression indexes help when the function is unavoidable
Common mistakes
- Formatting dates in WHERE clauses
- Doing arithmetic on the column instead of the constant
Follow-ups
- How would you index lower(email)?
- Is created LIKE '2026-02%' sargable in SQLite?
Tips
- Show the plan for both forms