SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 22 / 37

Middle

Which queries can a composite index (a, b, c) serve, and how should you order its columns?

Short answer

Index (a, b, c) is sorted by a, then b, then c (like a phone book sorted by last name, then first name), so it serves only the leftmost prefix: a, a + b, a + b + c. Column order: equality = first, range or ORDER BY column last.

Real queriesEquality columnsgo firstRange / ORDER BY columngoes lastColumns after a rangeonly filter

3 points to say:

  1. The index works for the leftmost prefix; after a range column, the later columns only filter.
  2. Filtering on b alone needs a skip scan (MySQL 8.0.13+, PostgreSQL 18+), worth it only when a has few values.
  3. Design indexes from real queries: a column always present as = matters more than a highly selective one.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.