Preserving ordering with WHERE IN() clause in MySQL


By ivan.jovanovic - Posted on 01 April 2008

Today I ran into the code that pulls from database list of elements with SELECT * FROM table WHERE id IN(2,5,3,16,22,56,48) where order of ids is important to be preserved after results found. When using SELECT this way you will get the results for every id but ordered by id in ascending order. I was looking around and found neat solution to make MySQL work for you to preserve the order of returned results. With ORDER BY FIELD clause like here SELECT * FROM table WHERE id IN (1,5,2,13,4) ORDER BY FIELD(id, 1,5,2,13,4) you can keep the initial ordering.

What is the catch. This way id field can not be used as indexed. Therefore, EXPLAIN SELECT * FROM table WHERE id IN (1,5,2,13,4) ORDER BY FIELD(id, 1,5,2,13,4) would give you the information that it is using filesort for results ordering which is not so nice. In general, when you have ids as the array with the ordering you need, it probably needs less resources to reorganize them in memory instead of letting MySQL doing it with filesort.

I'll take some banchmarking tests on this to see about the concrete numbers that confirm or negate my presumption.

Trackback URL for this post:

http://blog.ivanjovanovic.com/trackback/8
Tags

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Potentially problem-causing HTML tags are filtered.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.