Order for SELECT ... IN (5,100,23) queries

Updated . Posted . Visible to the public.

When doing a query like this:
SELECT id FROM users WHERE (users.id IN (899,1084,1095,100,2424,2429,2420))

the order of the returned records is undefined. To force the query to return the records in a given order, you have to add ORDER BY FIELD(id, 899, 1084, ...)

So the query looks like this:
SELECT id FROM users WHERE (users.id IN (899,1084,1095,100,2424,2429,2420)) ORDER BY FIELD(id,899,1084,1095,100,2424,2429,2420);

Thomas Eisenbarth
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Thomas Eisenbarth to makandra dev (2010-08-30 09:52)