CodeMilian
CodeMilian

Reputation: 1290

Sort by column index not column name

I have a select statement that is dynamic and having the ability to sort by column index rather than by name would make my life easier.

Example:

select id, name, description 
from table 
order by description 

Would like something like:

select id, name, description 
from table 
order by colindex(2)

Upvotes: 0

Views: 117

Answers (2)

n8wrl
n8wrl

Reputation: 19765

If you're building your SQL dynamically then store the column names in an array. That way you can build your order-by statement with an ordinal index and emit the real name of the column in the statement.

Upvotes: -1

FLICKER
FLICKER

Reputation: 6683

The answer is

select id, name, description 
from table 
order by 2

Sometimes it is the easiest way specially when you are working on dynamic SQL. But, as mentioned in comments, try to avoid using column index. I think they are going to remove it as it is bug pron.

Upvotes: 2

Related Questions