We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A hard sql problem, graded against 5 test cases (3 of them hidden).
Query-writing problems - joins, aggregation, window functions, and query tuning.
Reach for it when you see: A schema and a question about the data rather than a function signature.
More SQLproblems →A B-tree composite index `(a, b, c)` can serve a query if and only if:
- The leftmost columns are matched as equalities, and
- At most one trailing column is used as a range, and
- ORDER BY can ride along only if it's a continuation of the leading equality / range portion.
Algorithm:
1. Place all equality columns first (in any order; in practice, highest cardinality first for selectivity).
2. Append at most one range column.
3. If the range column is the same as the ORDER BY column, the index already supports the sort - done.
4. If there is no range column and the ORDER BY column is distinct, append the ORDER BY column.
5. If there is a range AND a distinct ORDER BY column, the ORDER BY can't be index-served - drop it from the index recommendation.
Why this matters in interviews: the difference between an indexed seek (O(log n + k)) and a full table scan + sort (O(n log n)) is many orders of magnitude. EXPLAIN ANALYZE reveals which one happened: look for "Index Scan using ..." vs "Seq Scan" + "Sort".
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
These apply to the pattern as a whole, not just this problem.