I want to perform a sort operation on some field. Is it advantageous making an index on that field. For example:
SELECT * FROM `users` WHERE `age`=33 ORDER BY `name`
In this query, I know that having an index on age is helpful, but would it be better if I maintain an index for name. Would there be a performance gain by indexing it. And the ORDER BY operation is frequently needed for other queries as well.
An index on
namealone would not be likely to help significantly with this query, but an index on(age, name)would.While it’s not entirely accurate, it’s often instructive to think of an index as a list of rows sorted by the keys in the index (e.g, sorted by
agefirst, then byname). In the case of your sample query, all the rows withage=33would naturally come out of the composite index sorted by name, saving you from doing a separate sort. Having a separate index fornamewouldn’t help the same way.