What does SQL clause "GROUP BY 1" mean? What does SQL clause "GROUP BY 1" mean? sql sql

What does SQL clause "GROUP BY 1" mean?


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


SELECT account_id, open_emp_id         ^^^^        ^^^^          1           2FROM accountGROUP 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.


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).