Junior
Is there a difference in the order of defining fields in a composite index? For example, there is a composite index (name, surname), but the query only has surname — will the index be used?
sobes.tech AI
Answer from AI
The order of fields in composite indexes is very important. An index (name, surname) is optimized for queries where filtering or sorting starts with the name field. If the query only uses surname, such an index is generally not used because the index is built on the first field, and searching without it is inefficient.
For example, the query WHERE name = 'Ivan' AND surname = 'Ivanov' efficiently uses the index (name, surname), but the query WHERE surname = 'Ivanov' does not.
If queries by surname are frequent, it is advisable to create a separate index on this field or change the order of fields in the composite index.