GROUP BY a, b VS GROUP BY b, a

Viewed 1230

I was wondering if there is any difference between order of grouping in GROUP BY a, b and GROUP BY b, a (I know the final result is the same). If so, would it affect the query's speed?

2 Answers

A group by clause just defines the unique combination of field(s) which would be considered a group. There is no meaning to the order these fields are stated.

It does matter if you have multiple-column indexes. You should define the GROUP BY columns in the order of the index.

So, if you have an index for (a,b) then you should use GROUP BY a, b and MySQL is able to take full advantage of the index.

See example

Related