views:

65

answers:

2

Considering this MySQL query:

SELECT
  someColumns
FROM
  someTable
WHERE
  someColumn IN ( value1, value2, value3 )

... how can I guarantee that the rowset comes out ordered in the exact order of the values given to the IN () clause? I presume this is not guaranteed without giving it an ORDER BY clause, is it?

PS.:
The values to the IN () clause will be an array of arbitrary data passed to the query by PHP (utilizing Zend Framework's select statement) in the following manner:

->where( 'someColumn in (?)', $theArrayWithValues );
+5  A: 

Use a CASE statement in the ORDER BY:

ORDER BY CASE someColumn
           WHEN value1 THEN 1
           WHEN value2 THEN 2
           WHEN value3 THEN 3
         END ASC

Assign the arbitrary values as you like. I don't normally include ASC in ORDER BY because it is implied if not defined, but I wanted to be explicit in case you want in DESC order.

OMG Ponies
Works like a charm. Thank you.
fireeyedboy
A: 

No, the order is not guaranteed - or rather, it will be the order the selected rows appear in the database.

If you know the values will belong to a strict set you can make the column an ENUM type with the order you want, and sorting on this field will sort by that order.

One simple way to order by certain values is this:

ORDER BY `someColumn`='value1' DESC, `someColumn`='value2' DESC, ...
DisgruntledGoat