Sobes.tech
Senior

In composite indexes, which should be placed first: equality or range?

sobes.tech AI

Answer from AI

It is generally recommended to place columns with equality conditions first, followed by columns with range conditions in composite indexes in databases. This is because the index is built on the order of columns, and the optimizer effectively uses the index when exact values are filtered first, then ranges.

For example, if you have an index on (user_id, created_at), and your query has a condition WHERE user_id = ? AND created_at > ?, you should put user_id (equality) first, then created_at (range).

If you change the order, for example (created_at, user_id), then with an equality condition on user_id and a range on created_at, the index will be used less efficiently.

Thus, the rule is:

  • Columns with equality conditions come first
  • Columns with range conditions come after

This improves selectivity and query performance.

In composite indexes, which should be placed first… - sobes.tech