Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep order from 'IN' clause

Tags:

sql

oracle

Is it possible to keep order from a 'IN' conditional clause?

I found this question on SO but in his example the OP have already a sorted 'IN' clause.

My case is different, 'IN' clause is in random order Something like this :

SELECT SomeField,OtherField
FROM TestResult 
WHERE TestResult.SomeField IN (45,2,445,12,789)

I would like to retrieve results in (45,2,445,12,789) order. I'm using an Oracle database. Maybe there is an attribute in SQL I can use with the conditional clause to specify to keep order of the clause.

like image 881
bAN Avatar asked Jan 03 '13 13:01

bAN


People also ask

How do you use ORDER BY clause?

The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query. Use ASC or DESC to specify the sorting order after the column name.

Does order matter in WHERE clause?

No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.

How do I get records in the same order in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How can I get SQL query result in same order as given by in clause?

in php u can do it like : <? php $my_array = array (3,6,1,8,9) ; $sql = 'SELECT * FROM table WHERE id IN (3,6,1,8,9)'; $sql . = "\nORDER BY CASE id\n"; foreach($my_array as $k => $v){ $sql .


2 Answers

There will be no reliable ordering unless you use an ORDER BY clause ..

SELECT SomeField,OtherField FROM TestResult  WHERE TestResult.SomeField IN (45,2,445,12,789) order by case TestResult.SomeField          when 45 then 1          when 2  then 2          when 445 then 3          ...          end 

You could split the query into 5 queries union all'd together though ...

SELECT SomeField,OtherField FROM TestResult  WHERE TestResult.SomeField = 4 union all SELECT SomeField,OtherField FROM TestResult  WHERE TestResult.SomeField = 2 union all ... 

I'd trust the former method more, and it would probably perform much better.

like image 148
David Aldridge Avatar answered Sep 25 '22 21:09

David Aldridge


Decode function comes handy in this case instead of case expressions:

SELECT SomeField,OtherField
FROM TestResult 
WHERE TestResult.SomeField IN (45,2,445,12,789)
ORDER BY DECODE(SomeField, 45,1, 2,2, 445,3, 12,4, 789,5)

Note that value,position pairs (e.g. 445,3) are kept together for readability reasons.

like image 38
Pero Avatar answered Sep 23 '22 21:09

Pero