Skip to the page

Indexes and query performance · Write code

Which queries can use a composite index

The 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

  1. Why does column order matter? Explain it with a phone book.
  2. What single index would serve both C and D best?
  3. What is PostgreSQL 18's skip scan, and when does it help?
  4. Would you also keep an index on customer_id alone?
  5. 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 checks created_at on each of that customer's entries, because status sits 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_id index is redundant. Unused indexes: pg_stat_user_indexes with idx_scan = 0 over a long enough time (check replicas too), or MySQL's sys.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 voice

Practise 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.

Start your free interview