Search code examples
sqlselectsql-order-bysybasesap-ase

Sybase Select WHERE IN given order


Is there a way to keep the order when using SELECT WHERE IN() in Sybase

There are two examples in mysql:

SELECT * FROM table WHERE id IN (118,17,113,23,72) 
ORDER BY FIELD(id,118,17,113,23,72)


SELECT * FROM table WHERE id IN (118,17,113,23,72) 
ORDER BY FIND_IN_SET(id, '118,17,113,23,72')

I need it in Sybase Ase.


Solution

  • You could break down the argument list with a case statement the explicitly assigns an ascending counter to the arguments and order according to that:

    SELECT   * 
    FROM     sometable 
    WHERE    id IN (118,17,113,23,72) 
    ORDER BY CASE id WHEN 118 THEN 1
                     WHEN 17  THEN 2
                     WHEN 113 THEN 3
                     WHEN 23  THEN 4
                     WHEN 72  THEN 5
              END ASC
    

    It's clunky as hell, but it should work.