Indexes and query performance · Write code
Which queries can use a composite index
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
We have an index on orders(customer_id, status, created_at). For each of these four queries, does the index help, and how?
-- A
SELECT * FROM orders WHERE customer_id = 42 AND status = 'PAID';
-- B
SELECT * FROM orders WHERE status = 'PAID' AND created_at > now() - interval '1 day';
-- C
SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;
-- D
SELECT * FROM orders WHERE customer_id = 42 AND created_at > '2026-11-01';
Then
Follow-ups the interviewer asks next
- Why does column order matter? Explain it with a phone book.
- What single index would serve both C and D best?
- What is PostgreSQL 18's skip scan, and when does it help?
- Would you also keep an index on
customer_idalone? - How do you find indexes that are never used?
The answer
What a strong answer covers
- A: yes, it seeks on the first two columns (the leftmost prefix).
- B: there is no condition on
customer_id, so a normal B-tree can't seek. PostgreSQL 18 skip scan (and MySQL 8.0's skip-scan range access) can jump through the leading column, but only pays off when it has few distinct values; with millions of customers it won't. A separate(status, created_at)index fits. - C: it seeks to customer 42, but rows are ordered by status first, so they still need a sort by
created_at.(customer_id, created_at)gives the order for free. - D: it seeks on
customer_id, then checkscreated_aton each of that customer's entries, becausestatussits in between. - Rule of thumb: equality columns first, then the range or sort column. Design from the real queries, not "most selective first".
- A separate
customer_idindex is redundant. Unused indexes:pg_stat_user_indexeswithidx_scan = 0over a long enough time (check replicas too), or MySQL'ssys.schema_unused_indexes.
The red pen
Common traps
Avoid:"the order of columns doesn't matter"; "B uses the index because status is in it".
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.