Sobes.tech
Junior — Middle

How to correctly determine the sequence of fields when creating a composite index?

sobes.tech AI

Answer from AI

When creating a composite index, it is important to correctly determine the order of fields, as this affects the efficiency of search and index usage. The main rules:

  • Place the most selective (unique) fields at the beginning of the index — this will reduce the number of records checked.
  • Fields that are most frequently used for filtering or sorting should come first.
  • If the index is used for sorting, the order of fields should match the sorting order.

For example, if you have a table with fields country, city, user_id, and queries most often filter by country and city, then the index should be (country, city, user_id).