Click here to Skip to main content
15,886,693 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
SQL
select * from tablename where id in(3,1,6,2);

I am getting the result in ascending order.

I want to get in the order I given.(as 3,1,6,2).

How can i do that?
Posted
Updated 12-Dec-11 22:19pm
v2
Comments
Amir Mahfoozi 13-Dec-11 4:36am    
Do you use the above mentioned SQL exactly ? probably (3,1,6,2) is a select statement in your real environment. Isn't it ? If so provide that statement.
RAJI @Codeproject 13-Dec-11 4:57am    
(3,1,6,2) may varying..depend on condition.
Amir Mahfoozi 13-Dec-11 4:59am    
I meant that is it generated from a sub query or it is built from UI ?

1 solution

If that is the only thing you can order by, then you have to be fairly unpleasant:
SQL
SELECT * FROM tablename WHERE id IN (3, 1, 6, 2) ORDER BY
        (Case When id = 3 then 0
              When id = 1 then 1
              When id = 6 then 2
              When id = 2 then 3
              Else id End)
 
Share this answer
 
Comments
Amir Mahfoozi 13-Dec-11 6:10am    
+5 your solution is suitable since it seems that the OP makes the list at runtime so he/she can make the CASE part after making the IN part!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900