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;Without a suitable index, every row is read and sorted:
sql
EXPLAIN QUERY PLAN SELECT id, created FROM events WHERE user_id = 7 ORDER BY created DESC LIMIT 10;text
QUERY PLAN
SCAN events
USE TEMP B-TREE FOR ORDER BYWith an index on (user_id, created), the rows for user 7 are already in date order:
sql
CREATE INDEX ev_user_created ON events(user_id, created);
EXPLAIN QUERY PLAN SELECT id, created FROM events WHERE user_id = 7 ORDER BY created DESC LIMIT 10;text
QUERY PLAN
SEARCH events USING COVERING INDEX ev_user_created (user_id=?)The temp B-tree line is gone. The engine walks the index backwards from the latest date for user 7 and stops after 10 rows. For "latest N items per user" pages, this index shape is the standard answer.
The index must match the filter and sort: (created, user_id) would not avoid the sort for one user, because its rows are scattered through the index.
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;
EXPLAIN QUERY PLAN SELECT id, created FROM events WHERE user_id = 7 ORDER BY created DESC LIMIT 10;
CREATE INDEX ev_user_created ON events(user_id, created);
EXPLAIN QUERY PLAN SELECT id, created FROM events WHERE user_id = 7 ORDER BY created DESC LIMIT 10;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- An index in ORDER BY order avoids sorting
- SQLite shows USE TEMP B-TREE FOR ORDER BY when it sorts
- With LIMIT, the engine can stop early
- Put the equality filter first, then the sort column
Common mistakes
- Indexing the sort column alone when a filter comes first
- Ignoring sort cost on pages that show 'latest' items
Follow-ups
- Can the same index serve ORDER BY created ASC?
- How does this relate to keyset pagination?
Tips
- Point out the missing temp B-tree line