SQL · Queries that survive scale
How do composite indexes and the leftmost prefix rule work?
Short answer
A composite index covers several columns in a defined order. It can serve queries that filter on a leftmost prefix of that order; a condition on a later column alone usually cannot use it efficiently.
Column order in a composite index is not cosmetic. Think of the index as sorted first by the first column, then by the second within equal first values. A query must provide the leading columns to navigate that order.
CREATE INDEX idx_events_user_type_time
ON events (user_id, event_type, created_at DESC);
SELECT id, created_at
FROM events
WHERE user_id = 42
AND event_type = 'login'
ORDER BY created_at DESC
LIMIT 20;Ordering rules of thumb
- Put equality-filtered columns first, then range or sort columns
- The index can serve user_id, or user_id plus event_type, or all three
- A query filtering only on event_type generally cannot use this index
- A range condition on an earlier column limits use of later columns for ordering
- A covering index with INCLUDE columns can avoid table lookups
For a query that filters by user_id and sorts by created_at, an index on (user_id, created_at) is a better fit than one on (created_at, user_id). Match the index order to the query's equality and ordering needs.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does the order of columns matter?
- 2Can an index on (a, b) serve a query filtering only on b?
- 3Where should range predicates go in a composite index?
- 4What is an INCLUDE column?
Say it in the interview
A composite index is sorted by its columns in order, so a query can navigate it only when it constrains a leftmost prefix. I put equality columns first and range or sort columns after them. An index on user_id and created_at can serve filters on user_id and ordering by created_at, but an index on created_at first would not serve a user_id-only filter as well. I consolidate overlapping indexes to control write cost.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.