← Back to SQL, page 11

sql-0211 · Easy fresher

What is an index, and how can you tell whether a query uses one in SQLite?

An index is a separate sorted structure, usually a B-tree, that maps column values to rows so the engine can find matches without reading the whole table. In SQLite, EXPLAIN QUERY PLAN shows SCAN for a full table read and SEARCH ... USING INDEX when an index narrows the lookup.

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 an index on user_id, the engine must read every row:

sql
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;
text
QUERY PLAN
SCAN events

After creating one, the plan changes to a search:

sql
CREATE INDEX events_user ON events(user_id);
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;
text
QUERY PLAN
SEARCH events USING INDEX events_user (user_id=?)

The table is a heap of 2,000 rows; the index keeps user_id values sorted with pointers back to each row, so finding user 7 takes a few page reads instead of 2,000 row checks.

Indexes cost disk space and slow down every INSERT, UPDATE and DELETE that touches the indexed columns, because the index must be updated too. Add them for real query patterns, not for every column.

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 * FROM events WHERE user_id = 7;

CREATE INDEX events_user ON events(user_id);
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • An index is a sorted lookup structure, usually a B-tree
  • EXPLAIN QUERY PLAN shows SCAN or SEARCH
  • Indexes speed reads and slow writes
  • Create indexes for actual query patterns

Common mistakes

  • Indexing every column 'just in case'
  • Assuming an index is used without checking the plan

Follow-ups

  • Why might an index not be used even when it exists?
  • What is a covering index?

Tips

  • Show a plan before and after