views:

60

answers:

2

Say I have a query "select * from clauses where id in (0,2,5,1,3)" and I actually want the rows returned in the same order they are specified the where clause. The order of the IDs will change from query to query and there is no pattern to the order.

I know it's possible to alter the data model, create temp tables, etc. But trust me that those types of solutions will not work in my situation. I also am unable to alter the order of the result objects in my application code.

I'm also aware that different database engines sort things differently, there are no guarantees in some situations blah blah blah. I just want to no, is this possible?

I'll be using mysql or sql server if that helps :)

+5  A: 

On MySQL, you can use FIND_IN_SET:

ORDER BY FIND_IN_SET(id, '0,2,5,1,3')

The most portable means of ordering would be to use a CASE expression:

ORDER BY CASE id
           WHEN 0 THEN 1
           WHEN 2 THEN 2
           WHEN 5 THEN 3
           WHEN 1 THEN 4
           WHEN 3 THEN 5
         END
OMG Ponies
Yeah, building that case statement will be tricky but I don't see a way out of it :(
oreoshake
+5  A: 
Select ..
From Clauses
Where Id In(0,2,5,1,3)
Order By Case Id
                When 0 Then 1
                When 2 Then 2
                When 5 Then 3
                When 1 Then 4
                When 3 Then 5
                ...
                End
Thomas