Pick the fix
The hottest query is WHERE tenant_id = $1 AND status = 'open' ORDER BY created_at DESC LIMIT 20. Best single index?
Hint 1 of 1
Equality columns first; what comes last?
Choose an answer, then open Show answer below to check it.
Plan shape checked with EXPLAIN on PostgreSQL 17; page counts are a toy table
Text version
WHERE customer_id = 7 (Index Scan):
- Root: c7–c9
- Inner: c7
- Leaf: c7 Mon, c7 Tue, c7 Wed
- Table: H3, H6
WHERE created_at > … (Index Scan):
- Root: not used
- Inner: not used
- Leaf: c7 Mon, c7 Tue, c7 Wed
- Table: H1
| Scenario | Plan | Index pages | Table pages |
|---|---|---|---|
| WHERE customer_id = 7 | Index Scan | 5 | 2 |
| WHERE created_at > … | Index Scan | 3 | 1 |
Show answer
Answer: A (tenant_id, status, created_at DESC)
Correct. Two equality columns narrow to one slice, already sorted by created_at, so LIMIT stops after 20 entries.
A B-tree is sorted by its columns left to right. With the equality columns first, all of one tenant's open orders sit together, already sorted by created_at, so the query reads 20 entries and stops.
Why not the others?
- B
(created_at, tenant_id, status). Range or sort column first: the scan walks all tenants. - C
(status). Low selectivity, and the sort still happens. - D Three single-column indexes. Can be combined with bitmaps, but not for an ordered LIMIT scan.