Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning query results in predefined order

Is it possible to do a SELECT statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 and returning them in that order, based on nothing more than the ID field?

Both these statements return them in the same order:

SELECT id FROM table WHERE id in (7,2,5,9,8) 
SELECT id FROM table WHERE id in (8,2,5,9,7)
like image 919
kari.patila Avatar asked Sep 25 '08 16:09

kari.patila


People also ask

How to specify order in SQL?

The SQL ORDER BY Keyword 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.

What is default sorting order in SQL?

By default, SQL Server sorts out results using ORDER BY clause in ascending order.

How to use ORDER BY condition in SQL?

SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.

Can we use SELECT statement in ORDER BY clause?

SQL queries initiated by using a SELECT statement support the ORDER BY clause. The result of the SELECT statement is sorted in an ascending or descending order.


2 Answers

I didn't think this was possible, but found a blog entry here that seems to do the type of thing you're after:

SELECT id FROM table WHERE id in (7,2,5,9,8) 
ORDER BY FIND_IN_SET(id,"7,2,5,9,8");

will give different results to

SELECT id FROM table WHERE id in (7,2,5,9,8) 
ORDER BY FIND_IN_SET(id,"8,2,5,9,7");

FIND_IN_SET returns the position of id in the second argument given to it, so for the first case above, id of 7 is at position 1 in the set, 2 at 2 and so on - mysql internally works out something like

id | FIND_IN_SET
---|-----------
7  | 1
2  | 2
5  | 3

then orders by the results of FIND_IN_SET.

like image 150
ConroyP Avatar answered Oct 18 '22 21:10

ConroyP


Your best bet is:

ORDER BY FIELD(ID,7,2,4,5,8) 

...but it's still ugly.

like image 22
Matthias Winkelmann Avatar answered Oct 18 '22 21:10

Matthias Winkelmann