Does the order of columns matter in a group by clause? Does the order of columns matter in a group by clause? sql-server sql-server

Does the order of columns matter in a group by clause?


No, the order doesn't matter for the GROUP BY clause.

MySQL and SQLite are the only databases I'm aware of that allow you to select columns which are omitted from the group by (non-standard, not portable) but the order doesn't matter there either.


SQL is declarative.

In this case, you have told the optimiser how you want the data grouped and it works out how to do it.

It won't evaluate line by line (procedural) and look at one column first

The main place column order matters is for indexes. col1, col2 is not the same as col2, col1. At all.


There's a legacy, non-standard feature of Microsoft SQL Server called ROLLUP. ROLLUP is an extension to the GROUP BY syntax and when it is used the order of the GROUP BY columns determines which columns should be grouped in the result. ROLLUP is deprecated however. The standard SQL alternative is to use grouping sets, which is supported by SQL Server 2008 and later versions.