Composite indexes and column order in SQL
A two-column index is one ordered list, so the leading column is the one you can search.
CREATE INDEX orders_by_customer_date
ON orders (customer_id, placed_at DESC);
EXPLAIN QUERY PLAN
SELECT
id,
total
FROM orders
WHERE customer_id = 42
ORDER BY placed_at DESC
LIMIT 10;
How it works
(a, b)serves a filter ona, and onaplusb— but not onbalone.- Put the equality column first and the range or sort column second.
- The index also satisfies the
ORDER BYwhen it matches its own order.
Keywords and builtins used here
BYCREATEDESCEXPLAINFROMINDEXLIMITONORDERSELECTWHERE
The run, in numbers
- Lines
- 11
- Characters to type
- 183
- Tokens
- 32
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 21 seconds.
Step 2 of 5 in Indexes, step 4 of 17 in Plans & performance.