MySQL specifying exact order with WHERE `id` IN (...)

Gray Fox picture Gray Fox · Jun 2, 2010 · Viewed 11.3k times · Source

Is there an easy way to order MySQL results respectively by WHERE id IN (...) clause? Example:

SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3)

to return

Article with id = 4
Article with id = 2
Article with id = 5
Article with id = 9
Article with id = 3

and also

SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3) LIMIT 2,2

to return

Article with id = 5
Article with id = 9

Update: to be more specific, I want to avoid tampering with the data in parentheses in WHERE articles.id IN (4, 2, 5, 9, 3), since those IDs are dynamic and automatically ordered.

Answer

bobince picture bobince · Jun 2, 2010

Yeah, kind of:

SELECT * FROM articles
WHERE articles.id IN (4, 2, 5, 9, 3)
ORDER BY FIND_IN_SET(articles.id, '4,2,5,9,3')

but this is non-standard SQL and smells a bit.