Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order resultset based on WHERE IN clause data

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 );
like image 891
Decent Dabbler Avatar asked Dec 30 '22 02:12

Decent Dabbler


2 Answers

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.

like image 75
OMG Ponies Avatar answered Jan 14 '23 17:01

OMG Ponies


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, ...
like image 30
DisgruntledGoat Avatar answered Jan 14 '23 15:01

DisgruntledGoat