Yes, ORDER BY can use column numbers instead of column names. These numbers represent the position of the column in your SELECT list (starting from 1).
How it Works
If your query is:
SELECT title, genre, price FROM books ORDER BY 2 ASC, 3 DESC;
In this case:
1refers totitle2refers togenre3refers toprice
So, ORDER BY 2, 3 DESC is exactly the same as ORDER BY genre, price DESC.
Pros and Cons
- Pros: It is faster to type and can be very handy when you are doing quick data exploration in the terminal.
- Cons: It is generally considered bad practice in production code or long scripts. This is because if someone changes the order of columns in the
SELECTstatement later, the sort order will break or change unexpectedly.
Example in your Environment:
Try this in your MySQL terminal:
-- Sort by genre (2nd column) then price (3rd column)
SELECT title, genre, price FROM books ORDER BY 2, 3 DESC;
You will notice the result is identical to the one you ran earlier using column names