Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly specify sort order for mysql query?

If I have:

ID | Title
1  | Shirt
2  | CD
3  | Cap
4  | Mp3
5  | Badge

If I want to sort by this order: 4, 2, 5, 3,1. Is there a way to do an sql query where you explicitly specify this? Something like:

select * from TABLE order by ID(4,2,5,3,1) ??
like image 351
coderama Avatar asked Oct 18 '11 05:10

coderama


People also ask

How do I sort a MySQL query?

The MySQL 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.

How do I sort a specific order in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


1 Answers

Actually, you were surprisingly close. It's a simple as:

select * from TABLE order by field(ID,4,2,5,3,1)
like image 62
Bohemian Avatar answered Sep 24 '22 06:09

Bohemian