If I have two columns, one with very high cardinality and one with very low cardinality (unique # of values), does it matter in which order I group by?
Here\'s an ex
Since this has not been mentioned here. The answers above are correct i.e. the order of the columns after the "group by" clause will not affect the correctness of the query (i.e. the sum amount).
However, the order of the rows being retrieved will vary based on the order of the columns specified after the "group by" clause. For example consider Table A with the following rows:
Col1 Col2 Col3
1 xyz 100
2 abc 200
3 xyz 300
3 xyz 400
SELECT *, SUM(Col3) FROM A GROUP BY Col2, Col1 will retrieve rows ordered by the Col2 in ascending order.
Col1 Col2 Col3 sum(Col3)
2 abc 200 200
1 xyz 100 100
3 xyz 300 700
Now change the ordering of column in group by to Col1, Col2. The retrieved rows are ordered asc by Col1.
i.e. select *, sum(Col3) from A group by Col1, Col2
Col1 Col2 Col3 sum(Col3)
1 xyz 100 100
2 abc 200 200
3 xyz 300 700
Note: The the summation amount (i.e. the correctness of the query) remains exactly the same.