What do the numbers refer to in a statement like ‘GROUP BY 1’ or ‘ORDER BY 2’?
When you see numbers after a
GROUP BY or
ORDER BY statement, they are referring to the columns that were selected in the query. These are called column reference numbers. The 1 signifies the first column selected, the 2 signifies the second column selected, and so on. Here’s an example:
SELECT alpha, bravo, charlie FROM table GROUP BY 1 ORDER BY 2;
In this query, 1 is referring to alpha and 2 is referring to bravo.
The main reason we use column reference numbers is because sometimes it can be a pain to type out a really long or complex column name. As you can imagine, it’s a whole lot easier typing a number than something like customer_order_number.