download

Why did our composite index still scan too many rows?

SQL~10 minReviewed 3 Dec 2026Free · No sign-in

Question

Your orders table stores UTC ISO-8601 timestamps and holds millions of rows across many tenants. A dashboard sums November 2026 spend for tenant 7, yet it stays slow after adding idx_orders_bad.

orders

idtenant_idcreated_atcents
172026-10-31T23:55:00Z1200
272026-11-01T00:00:00Z1500
372026-11-18T14:20:00Z2100
472026-11-30T23:45:00Z900
572026-12-01T00:00:00Z3000
682026-11-10T09:00:00Z5000
  1. Explain both indexing mistakes in the starter.
  2. Write a covering index and rewritten query so the planner narrows on tenant_id and created_at without touching the table.
"CODE · SQL"
CREATE INDEX idx_orders_bad
  ON orders (created_at, tenant_id);

SELECT SUM(cents) AS total_cents
FROM orders
WHERE tenant_id = 7
  AND substr(created_at, 1, 7) = '2026-11';
Show hints (3)
  1. "COLUMN ORDER RULE"

    Put equality filters before range filters in a B-tree index. Once a query ranges on the first column, the second column is no longer sorted across that range.

  2. "AVOID WRAPPED COLUMNS"

    Wrapping created_at in substr() or strftime() hides the column from index range bounds. Rewrite the filter as a half-open range on raw created_at.

  3. "MAKE IT COVERING"

    Add cents as the third index column. Then the query reads every needed column straight from the index without extra table lookups.

Show checked explanation

Put the equality column before the range column: index (tenant_id, created_at, cents). Rewrite substr(created_at, 1, 7) = '2026-11' as created_at >= '2026-11-01' AND created_at < '2026-12-01'. Now the planner seeks one tenant's November slice directly and reads cents from the covering index.

"SOLUTION · SQL"
CREATE INDEX idx_orders_cov
  ON orders (tenant_id, created_at, cents);

SELECT SUM(cents) AS total_cents
FROM orders
WHERE tenant_id = 7
  AND created_at >= '2026-11-01'
  AND created_at < '2026-12-01';
"OUTPUT"
total_cents
4500

Author-checked on SQLite 3.49.1: ran the starter and fixed queries plus EXPLAIN QUERY PLAN against the sample table and a 900-row table. PostgreSQL INCLUDE and index-only scan semantics checked against official documentation. Checked by an editor other than the author.

Walkthrough

The starter makes two classic B-tree mistakes that reinforce each other.

1. Wrapping created_at in substr(). A B-tree indexes raw created_at values, not substr(created_at, 1, 7). Wrapping a column in a function like substr() or strftime() makes the filter non-sargable, so the planner cannot use index range bounds on created_at. With (created_at, tenant_id), SQLite falls back to a full SCAN orders. Even with the right column order, substr() limits the lookup to (tenant_id=?) and reads every historical order for tenant 7.

2. Putting the range column first. With (created_at, tenant_id) and a fixed range filter, SQLite seeks November rows across all tenants (created_at>? AND created_at<?) and checks tenant_id = 7 afterward. Putting tenant_id first groups tenant 7's rows together in timestamp order.

3. Adding cents for a covering index. With (tenant_id, created_at), SQLite still visits the main table for each matching row to read cents. Adding cents at the end satisfies the whole query from the index alone (USING COVERING INDEX):

IndexFilter on created_atSQLite 3.49 EXPLAIN QUERY PLAN
(created_at, tenant_id)substr(created_at, 1, 7) = '2026-11'SCAN orders
(created_at, tenant_id)>= '2026-11-01' AND < '2026-12-01'SEARCH orders USING INDEX idx_orders_bad (created_at>? AND created_at<?)
(tenant_id, created_at, cents)substr(created_at, 1, 7) = '2026-11'SEARCH orders USING COVERING INDEX idx_orders_cov (tenant_id=?)
(tenant_id, created_at, cents)>= '2026-11-01' AND < '2026-12-01'SEARCH orders USING COVERING INDEX idx_orders_cov (tenant_id=? AND created_at>? AND created_at<?)

On the sample rows, tenant 7 matches rows 2, 3, and 4, summing 1500 + 2100 + 900 = 4500. Row 5 (2026-12-01T00:00:00Z) is excluded by < '2026-12-01', and row 6 belongs to tenant 8.

Common mistakes

  • Using created_at BETWEEN '2026-11-01' AND '2026-11-30' on full timestamps. String comparison drops 2026-11-30T23:45:00Z, returning 3600 instead of 4500.
  • Placing created_at before tenant_id in the index. The planner scans every tenant's November orders instead of jumping straight to tenant 7.
  • Filtering with strftime('%Y-%m', created_at) = '2026-11'. Like substr(), it hides the column from B-tree range bounds.
  • Adding every table column to make every index covering. Wide indexes slow down writes and bloat memory.

Follow-up questions

  • "Can this index also help a query that filters only by created_at?" Usually not well. Because tenant_id leads the index, a query without tenant_id cannot seek straight to one date slice, though SQLite may try a skip-scan when tenant_id has very few distinct values.
  • "How does PostgreSQL build a covering index without widening the search key?" Use CREATE INDEX ON orders (tenant_id, created_at) INCLUDE (cents). PostgreSQL stores cents only in leaf pages for index-only scans, keeping upper B-tree pages smaller.
  • "What if you also need ORDER BY created_at DESC LIMIT 20 for one tenant?" The same (tenant_id, created_at, cents) B-tree already stores each tenant's rows in created_at order. The engine can walk that slice backward and stop after 20 rows without sorting.

What a strong answer covers

Applies equality-before-range column ordering, replaces substr() with a half-open range that keeps November 30 timestamps, explains covering indexes, and reads EXPLAIN QUERY PLAN to confirm both bounds.

Open in interactive practice deck →

Original OfferVibe question. SQLite Multi-Column Indices · SQLite Covering Indexes · SQLite EXPLAIN QUERY PLAN · PostgreSQL Multicolumn Indexes · PostgreSQL Index-Only Scans.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.