Order by Clause with Column_Index instead of Column Name





5.00/5 (2 votes)
A tip enable you to learn how to use Column_Index instead of Column Name with Order by clause
Its a very general and regular ways to use
when Using Column Index instead of Column Name for same query
Note :- Column Index can be changed as 1,2,3,etc based on column name condition
Reference Link :- Matt Berseth Articles[^]
Note :- ORDER BY clause is only Clause where we can you use the ordinal position[Column Numbers], because it's based on the column(s) specified in the SELECT clause.
its generally recommended that to use Column Name instead of Column Number. but in some cases using Column Number can be useful like it can be used it in a dynamic sql where column names are unknown.
for getting practical way you can follow this[^] blog.
Order by
clause with Column Name to Specifies the sort order used on columns returned in a SELECT statement.
Syntax :-
order by columnname asc/descI am also using the same method but do you know we can use Column Index (Integer representing the position of column name) instead of specifying the name or column alias in a SQL Server Order By expression. As:-
order by Column_Index_Number asc/descwe can use both queries because both of these queries having the same results. let check both syntax and result too here I am going to query based on AdventureWork database Example :- Getting top 10 value from Employee table based on EmployeeID in asc order
select top 10 * from HumanResources.Employee order by EmployeeID ascoutput will be as given below :-

select top 10 * from HumanResources.Employee order by 1 ascthen output will be same as given below :-
