While working with dynamic queries or otherwise when we are not sure of the number of columns that will be returned from the query or simply due to laziness for typing the entire column name we can use the index of the column by whom we want our result set to be sorted.
For instance lets say my dynamic query returns 4 to 10 columns randomly and we want the result set to be sorted by the second column in any which case we can simply write order by 2 in place of order by second column.
Eg.
1 2 3 |
select firstname, lastname, dob, gender, emailaddress from employee order by lastname go select firstname, lastname, dob, gender, emailaddress from employee order by 2 |
both the above cases will give the same result
Post comments if this helps