← Back to SQL, page 11

sql-0216 · Medium mid

How can a partial index help a queue table where only a few rows are pending?

Index only the rows the hot query reads: CREATE INDEX ... ON jobs(created) WHERE status = 'pending'. The index stays tiny while the table grows with finished jobs, and queries with the same WHERE condition can use it. Both SQLite and PostgreSQL support partial indexes.

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;

Only 40 of 2,000 rows are refunds here, standing in for pending jobs:

sql
CREATE INDEX ev_refunds ON events(created) WHERE kind = 'refund';
EXPLAIN QUERY PLAN SELECT id FROM events WHERE kind = 'refund' ORDER BY created LIMIT 5;
text
QUERY PLAN
SCAN events USING COVERING INDEX ev_refunds

The plan reads the partial index, which holds only the 40 refund rows, so even a full pass over it is cheap. The query's WHERE includes the index's condition, so the planner can use the small index and read rows already in created order. A query without kind = 'refund' cannot use it, because the index does not contain other rows.

Size matters: a full index on created would hold 2,000 entries; this one holds 40. For queue tables where most rows are 'done', that keeps inserts and lookups cheap.

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_refunds ON events(created) WHERE kind = 'refund';
EXPLAIN QUERY PLAN SELECT id FROM events WHERE kind = 'refund' ORDER BY created LIMIT 5;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A partial index covers only rows matching its WHERE
  • Queries must imply the same condition to use it
  • Ideal for small hot subsets such as pending work
  • Smaller indexes are cheaper to maintain

Common mistakes

  • Writing the query condition differently from the index condition
  • Using a partial index for queries that need all rows

Follow-ups

  • How would you pick the next job safely with several workers?
  • What other columns might the partial index include?

Tips

  • Mention the size benefit