devxlogo

Sorting

Sorting

Question:
I have a select query “Select * from Table where ID in (8, 2,3,78,32,1,7)” that I want returned in the same order that the IDs are in in the IN statement. By default SQL will return them sorted by the primary key (which is the ID). How can I do this?

Answer:
There is no easy way to specify your own order in the order clause. You would have to create another table with your values (8, 2,3,78,32,1,7) and their desired sequence and use that table in your select and order by. For example:

create table myorder( value int, sequence int)insert into myorder values (8,1)

etc..and then select …from …where id = myorder.valueorder by myorder.sequence

devx-admin

Share the Post: