sqlsql-serverlist

SQL - order by list order


I have the following query that returns rows based on a comma seperated list

Select * from Table where RecordID in (22,15,105,1,65,32)

I would like the results of this query to return to in the order of the ID's in the list. Is that possible with SQL?

Thanks in advance


Solution

  • If you need the output to appear in a particular order, then you need to specify that order, using something the server can sort. Not knowing which engine you're working against, the general scheme would be to create a temp table or use rowset constructors to pair each record ID with its desired sort order.

    E.g. (SQL Server)

    declare @T table (RecordID int,Position int)
    insert into @T (RecordID,Position)
    select 22,1 union all
    select 15,2 union all
    select 105,3 union all
    select 1,4 union all
    select 65,5 union all
    select 32,6
    
    select * from Table t inner join @T t2 on t.RecordID = t2.RecordID order by t2.Position