A query filters on column a with equality and on column b with a range. In what order should a two-column index list them?
Sketch your own answer first, then compare it with the one below.
A strong answer
Put the equality column first. Entries in a composite index are sorted by the first column, then by the second inside each value of the first. With a fixed value of a, the entries for b are contiguous, so a range on b becomes one scan.
With the range column first, the matching entries for a are scattered through the range, and the engine has to filter many entries it reads.
The same index also serves queries on a alone, and cannot serve a query on b alone well. A good answer says the index follows the leftmost prefix rule and relates it to sorted order.
Sources
- PostgreSQL Global Development Group (2024). Multicolumn Indexes.