Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 example:

select       dimensionName,       dimensionCategory,       sum(someFact) from SomeFact f join SomeDim d on f.dimensionKey = d.dimensionKey group by      d.dimensionName,  -- large number of unique values     d.dimensionCategory -- small number of unique values 

Are there situations where it matters?

like image 234
Jeff Meatball Yang Avatar asked Jun 17 '10 18:06

Jeff Meatball Yang


People also ask

Does order matter in ORDER BY clause?

The Order by clause does not affect the ordering of the records in the source table or changing the physical structure of the table. It is just a logical re-structuring of physical data. Next, add the SQL Order By clause in the query.

Can we use column position in ORDER BY clause?

Note: I would not recommend using column position in Order By clause. You should always use a column name in Order by clause.

Is ORDER BY mandatory for GROUP BY?

The ORDER BY clause is not strictly necessary. It's up to you to decide whether you want the result set ordered. However, given the whole point of GROUP BY , the following is recommended: You probably want the data displayed in the same order as per the GROUP BY clause, to make the grouping more apparent.

Does order of column matter in SQL?

Column order does not matter while creating a table. We can arrange the columns while retrieving the data from the database. Primary key can be set to any column or combination of columns.


1 Answers

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.

like image 79
OMG Ponies Avatar answered Oct 10 '22 17:10

OMG Ponies