Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining order in MySQL "IN" query

Tags:

sql

mysql

I have the following table

DROP TABLE IF EXISTS `test`.`foo`; CREATE TABLE  `test`.`foo` (   `id` int(10) unsigned NOT NULL auto_increment,   `name` varchar(45) NOT NULL,   PRIMARY KEY  (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

Then I try to get records based on the primary key

SELECT * FROM foo f where f.id IN (2, 3, 1); 

I then get the following result

+----+--------+ | id | name   | +----+--------+ |  1 | first  | |  2 | second | |  3 | third  | +----+--------+ 3 rows in set (0.00 sec) 

As one can see, the result is ordered by id. What I'm trying to achieve is to get the results ordered in the sequence I'm providing in the query. Given this example it should return

+----+--------+ | id | name   | +----+--------+ |  2 | second | |  3 | third  | |  1 | first  | +----+--------+ 3 rows in set (0.00 sec) 
like image 825
msp Avatar asked Oct 27 '09 15:10

msp


People also ask

How do I sort a MySQL query?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Can we use ORDER BY in update query in MySQL?

MySQL UPDATE UPDATE with ORDER BY and LIMITIf the ORDER BY clause is specified in your update SQL statement, the rows are updated in the order that is specified. If LIMIT clause is specified in your SQL statement, that places a limit on the number of rows that can be updated.

Does the order in queries matter?

The order doesn't matter, actually, so you are free to order them however you'd like.


1 Answers

As the other answer mentions: the query you posted has nothing about what order you'd like your results, just which results you'd like to get.

To order your results, I would use ORDER BY FIELD():

SELECT * FROM foo f where f.id IN (2, 3, 1) ORDER BY FIELD(f.id, 2, 3, 1); 

The argument list to FIELD can be variable length.

like image 69
Ty W Avatar answered Oct 04 '22 09:10

Ty W