Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do comma-separated integers in a GROUP BY statement accomplish?

Tags:

sql

group-by

I have a query like this:

SELECT col1, col2, col3, col4, col5, SUM(col6) AS total
FROM table_name
WHERE col1 < 99999
GROUP BY 1,2,3,4,5

What does the GROUP BY statement actually accomplish here? The query does not work properly without the comma-separated integers.

like image 678
James Skidmore Avatar asked Jun 17 '11 00:06

James Skidmore


1 Answers

It is equivalent to writing:

SELECT col1, col2, col3, col4, col5, SUM(col6) AS total
  FROM table_name
 WHERE col1 < 99999
 GROUP BY col1, col2, col3, col4, col5

The numbers are the values/columns in the select-list expressed by ordinal position in the list, starting with 1.

The numbers used to mandatory; then the ability to use the expressions in the select-list was added. The expressions can get unwieldy, and not all DBMS allow you to use 'display labels' or 'column aliases' from the select-list in the GROUP BY clause, so occasionally using the column numbers is helpful.

In your example, it would be better to use the names - they are simple. And, in general, use names rather than numbers whenever you can.

like image 189
Jonathan Leffler Avatar answered Nov 14 '22 22:11

Jonathan Leffler