Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL order by sequence of IN values in query

Tags:

mysql

For example I have this code:

SELECT *
FROM table_name
WHERE column_name IN (value6,value4,value11,value19)

Is there a way to order the result in that exact sequence in the query? The code above returns the default ordering of table_name, completely disregarding the sequence of IN values. I know I can do additional coding in PHP to properly order them according to the IN values but that would create a significant overhead.

like image 706
user614382 Avatar asked Feb 12 '11 17:02

user614382


Video Answer


1 Answers

SELECT 
  * 
FROM 
  table_name 
WHERE column_name IN (value6,value4,value11,value19) 
ORDER BY FIELD(column_name,value6,value4,value11,value19)

Explanation here: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field

  • FIELD(str,str1,str2,str3,...)

Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

like image 140
Mchl Avatar answered Oct 11 '22 11:10

Mchl