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;The index has user_id only, so fetching amount requires a trip to the table for each match:
sql
CREATE INDEX ev_user ON events(user_id);
EXPLAIN QUERY PLAN SELECT user_id, amount FROM events WHERE user_id = 7;text
QUERY PLAN
SEARCH events USING INDEX ev_user (user_id=?)With amount added to the index, the query is satisfied from the index:
sql
CREATE INDEX ev_user_amount ON events(user_id, amount);
EXPLAIN QUERY PLAN SELECT user_id, amount FROM events WHERE user_id = 7;text
QUERY PLAN
SEARCH events USING COVERING INDEX ev_user_amount (user_id=?)The saving is largest when many rows match, since each table visit is a random read. PostgreSQL calls this an index-only scan and lets you add non-key payload columns with INCLUDE (amount); it also depends on the visibility map being current, which VACUUM maintains (not run here).
Covering indexes are wider, so they cost more space and write work. Use them for hot queries, not as a default.
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_user ON events(user_id);
EXPLAIN QUERY PLAN SELECT user_id, amount FROM events WHERE user_id = 7;
CREATE INDEX ev_user_amount ON events(user_id, amount);
EXPLAIN QUERY PLAN SELECT user_id, amount FROM events WHERE user_id = 7;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- A covering index contains all columns the query uses
- SQLite shows USING COVERING INDEX
- It avoids reading the table rows
- PostgreSQL supports INCLUDE columns for this
Common mistakes
- Adding many columns to every index
- Selecting * and wondering why the index is not covering
Follow-ups
- How would you cover SELECT SUM(amount) WHERE user_id = ?
- What does INCLUDE add over a longer key?
Tips
- Compare the two plans side by side