Can I order by IN value

mysql, sql

Solution

You might consider using the `FIND_IN_SET` or `FIELD` functions to organize your results, if you already know the IDs beforehand.

SELECT 
    item_id,
    item_title,
    item_source
FROM items
WHERE item_id IN ('1676','1559','1672')
ORDER BY FIELD(item_id, '1676', '1559', '1672')

or

ORDER BY FIND_IN_SET(item_id, '1676,1559,1672')

The drawback, of course, is that you're specifying the IDs twice. I'm thinking pretty much any reasonably performing solution will do so, though. The only way to get around that would be to have a sort order field or something like that.

Problem

Can I sort by the value of an IN query? The following defaults to "order item_id lowest first" but i actually want the sort as entered... is this possible? e.g. ``` select item_id, item_title, item_source from items where item_id IN ('1676','1559','1672') ``` I want to return: ``` item_id item_title item_source ------- ---------- ----------- 1676 item_a source_a 1559 item_f source_f 1672 item_c source_c ```

Original source