Read more

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

Thomas Eisenbarth
August 30, 2010Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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);

Posted by Thomas Eisenbarth to makandra dev (2010-08-30 11:52)