Why did our composite index still scan too many rows?
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
| id | tenant_id | created_at | cents |
|---|---|---|---|
| 1 | 7 | 2026-10-31T23:55:00Z | 1200 |
| 2 | 7 | 2026-11-01T00:00:00Z | 1500 |
| 3 | 7 | 2026-11-18T14:20:00Z | 2100 |
| 4 | 7 | 2026-11-30T23:45:00Z | 900 |
| 5 | 7 | 2026-12-01T00:00:00Z | 3000 |
| 6 | 8 | 2026-11-10T09:00:00Z | 5000 |
- Explain both indexing mistakes in the starter.
- Write a covering index and rewritten query so the planner narrows on
tenant_idandcreated_atwithout touching the table.
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)
- "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.
- "AVOID WRAPPED COLUMNS"
Wrapping
created_atinsubstr()orstrftime()hides the column from index range bounds. Rewrite the filter as a half-open range on rawcreated_at. - "MAKE IT COVERING"
Add
centsas 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.
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';
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):
| Index | Filter on created_at | SQLite 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 drops2026-11-30T23:45:00Z, returning3600instead of4500. - Placing
created_atbeforetenant_idin the index. The planner scans every tenant's November orders instead of jumping straight to tenant7. - Filtering with
strftime('%Y-%m', created_at) = '2026-11'. Likesubstr(), 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_idleads the index, a query withouttenant_idcannot seek straight to one date slice, though SQLite may try a skip-scan whentenant_idhas 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 storescentsonly 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 increated_atorder. 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 →