Monday, March 4, 2013

Preserving Ordering With WHERE in() Clause in MySQL



Today I ran into the code that pulls from database list of elements with
1
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
1
2
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,
1
2
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.

No comments:

Post a Comment