← Back to SQL, page 11

sql-0219 · Hard senior

Can SQLite use indexes for WHERE user_id = 7 OR kind = 'refund' when each column has its own index?

Yes: SQLite can run a MULTI-INDEX OR plan, searching each index separately and combining the row ids, but only when every OR branch has a usable index. PostgreSQL does the same with a BitmapOr of bitmap index scans. Rewriting as UNION is the manual equivalent.

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_user ON events(user_id);
CREATE INDEX ev_kind ON events(kind);
sql
EXPLAIN QUERY PLAN SELECT id FROM events WHERE user_id = 7 OR kind = 'refund';
text
QUERY PLAN
MULTI-INDEX OR
  INDEX 1
    SEARCH events USING INDEX ev_user (user_id=?)
  INDEX 2
    SEARCH events USING INDEX ev_kind (kind=?)

The plan shows a MULTI-INDEX OR with one index search per branch. Dropping the index on kind forces a full scan, because the second branch cannot be answered from an index:

sql
DROP INDEX ev_kind;
EXPLAIN QUERY PLAN SELECT id FROM events WHERE user_id = 8 OR kind = 'refund';
text
QUERY PLAN
SCAN events

A UNION rewrite does the same job by hand and is sometimes clearer or faster on engines that handle OR poorly:

text
SELECT id FROM events WHERE user_id = 7
UNION
SELECT id FROM events WHERE kind = 'refund';

The general lesson: an OR is only as indexable as its least indexable branch.

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);
CREATE INDEX ev_kind ON events(kind);

EXPLAIN QUERY PLAN SELECT id FROM events WHERE user_id = 7 OR kind = 'refund';

DROP INDEX ev_kind;
EXPLAIN QUERY PLAN SELECT id FROM events WHERE user_id = 8 OR kind = 'refund';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SQLite can combine indexes for OR (MULTI-INDEX OR)
  • Every branch needs a usable index
  • PostgreSQL uses BitmapOr for the same idea
  • UNION is a manual alternative

Common mistakes

  • Expecting an index on one OR branch to help
  • Rewriting with UNION ALL and getting duplicates

Follow-ups

  • How would a composite index help an AND instead?
  • When is UNION faster than OR?

Tips

  • State the least-indexable-branch rule