Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL specify arbitrary order by id

Is it possible to specify an arbitrary order for a MySQL SELECT statement? E.g.,

SELECT * FROM table_name WHERE id IN (1, 3, 2, 9, 7) ORDER BY (1, 3, 2, 9, 7);

The order of the numbers listed directly after IN do not seem to matter.

like image 614
ma11hew28 Avatar asked Dec 01 '10 17:12

ma11hew28


People also ask

How do you select order by specific ids?

The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for ascending).

Where do we use Order By clause in mysql?

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.

Is order by a clause in mysql?

The MYSQL ORDER BY Clause is used to sort the records in ascending or descending order.


1 Answers

FIND_IN_SET function will do the trick

SELECT * FROM table_name WHERE id IN (1, 3, 2, 9, 7) ORDER BY FIND_IN_SET(id, '1,3,2,9,7');

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

EDIT: Note the lack of spaces in the string argument of the find_in_set function.

like image 195
The Scrum Meister Avatar answered Sep 30 '22 20:09

The Scrum Meister