Can `ORDER BY` use column numbers?

QuestionsQuestions8 SkillsProDec, 25 2025
0104

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:

  • 1 refers to title
  • 2 refers to genre
  • 3 refers to price

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 SELECT statement 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

0 Comments

no data
Be the first to share your comment!