What does SQL clause "GROUP BY 1" mean?

MysqlSqlGroup By

Mysql Problem Overview


Someone sent me a SQL query where the GROUP BY clause consisted of the statement: GROUP BY 1.

This must be a typo right? No column is given the alias 1. What could this mean? Am I right to assume that this must be a typo?

Mysql Solutions


Solution 1 - Mysql

It means to group by the first column regardless of what it's called. You can do the same with ORDER BY.

Solution 2 - Mysql

SELECT account_id, open_emp_id
         ^^^^        ^^^^
          1           2

FROM account
GROUP BY 1;

In above query GROUP BY 1 refers to the first column in select statement which is account_id.

You also can specify in ORDER BY.

> Note : The number in ORDER BY and GROUP BY always start with 1 not with 0.

Solution 3 - Mysql

In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.

This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.

If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).

Solution 4 - Mysql

It will group by first field in the select clause

Solution 5 - Mysql

That means *"group by the 1st column in your select clause". Always use GROUP BY 1 together with ORDER BY 1.

You can also use GROUP BY 1,2,3... It is convenient, but you need to pay attention to that condition; the result may not be what you want if someone has modified your select columns and it's not visualized.

Solution 6 - Mysql

It will group by the column position you put after the group by clause.

for example if you run 'SELECT SALESMAN_NAME, SUM(SALES) FROM SALES GROUP BY 1' it will group by SALESMAN_NAME.

One risk on doing that is if you run 'Select *' and for some reason you recreate the table with columns on a different order, it will give you a different result than you would expect.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSpencerView Question on Stackoverflow
Solution 1 - MysqlYuckView Answer on Stackoverflow
Solution 2 - MysqlVishwanath DalviView Answer on Stackoverflow
Solution 3 - Mysqlvol7ronView Answer on Stackoverflow
Solution 4 - MysqlDaan GeurtsView Answer on Stackoverflow
Solution 5 - Mysql张艳军View Answer on Stackoverflow
Solution 6 - MysqlwdoeringView Answer on Stackoverflow