Some SQL databases allow ORDER BY to reference the position of a selected column instead of its column name or alias.
Column-position ordering can shorten queries, but understanding its limitations helps you write maintainable SQL.
Sort the result using the second selected column.
SELECT
EmployeeName,
Salary
FROM Employees
ORDER BY 2 DESC;
This technique may appear in existing SQL code, quick analysis, and reporting queries, although explicit column names are generally easier to maintain.
- ORDER BY can support column positions in many databases.
- Position 1 refers to the first selected expression.
- Position 2 refers to the second selected expression.
- It can make queries shorter.
- Explicit column names are usually clearer.
What does ORDER BY 2 mean?
It means sorting by the second expression listed in the SELECT clause, where the database supports ordinal ordering.
Why might column positions be avoided?
Changing the SELECT column order can unintentionally change the sorting, making the query harder to maintain.