Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite and custom order by

I have a table with categories:

ID  Category "1","Baking"    "3","Family"    "4","Entertaining"    "5","Children"    "6","Desserts"    

Now I would like to order the result of the select statement to

ID  Category "4","Entertaining"    "3","Family"   "1","Baking"    "5","Children"    "6","Desserts"   

for example. In MySQL, you'd do it like this:

SELECT * FROM CATEGORIES ORDER BY FIELD (ID, 4,3,1,5,6); 

How would you do it in SQLite though? I don't have an "order by" field.

like image 890
ChrisB Avatar asked Jul 21 '10 21:07

ChrisB


2 Answers

ORDER BY    CASE ID     WHEN 4 THEN 0     WHEN 3 THEN 1     WHEN 1 THEN 2     WHEN 5 THEN 3     WHEN 6 THEN 4   END 
like image 146
Tomalak Avatar answered Sep 19 '22 15:09

Tomalak


A second way of doing it (the first one being with CASE WHEN ... THEN END as already stated in other answers) is:

ORDER BY ID=4 DESC,          ID=3 DESC,          ID=1 DESC,          ID=5 DESC,          ID=6 DESC 
like image 21
Thomas Baruchel Avatar answered Sep 22 '22 15:09

Thomas Baruchel