Skip to content
Advertisement

SQL Server Select query with IN() and order by the same

I need a SELECT query with an IN clause, as well as Order by:

select * 
from table 
where column_id IN (5,64,2,8,7,1) 

This code returns 1, 2, 5, 7, 8, 64.

Now I need to return the same select in order

Output needs to be: 5, 64, 2, 8, 7, 1

In Mysql, field option is there, but SQL Server does not have such a field option.

Advertisement

Answer

In SQL-Server, when you want to order by something, you have to specifically spell it out.

Try this

select * from table where column_id IN (5,64,2,8,7,1)
order by
case column_id
    when 5 then 1
    when 64 then 2
    when 2 then 3
    when 8 then 4
    when 7 then 5
    when 1 then 6
    else 10
end;
9 People found this is helpful
Advertisement