views:

41

answers:

2

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.

+3  A: 
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
Tomalak
+1: Blast! Faster than me.
OMG Ponies
@OMG: For ONCE! :-D
Tomalak
+1 ya me too, I was just typing it out. The other option of course is to create an attribute that acts as a priority, then you can just order by the priority. This is not the ideal way, but a solution I have had to use in the past.
northpole
For speed with large data sets, I would probably create an indexed helper table that contains the IDs and their desired order, and then join against it and order by its indexed column. Not sure how SQLite would handle this, but "bigger" DB engines would probably benefit, as the CASE expression is not optimal for ordering.
Tomalak
A: 

I don't have an "order by" field

Why not?

If it is because the sort order is application sepcific then do the sort in the application rather than in the database.

If it is because the sort order is specific to just this one query then encode it in the query HOWEVER I strongly suggest you make this transparent to the calling application e.g. (Standard SQL syntax):

SELECT T2.ID, T2.Category, 
       T2.query_name_here_sort_order
  FROM (
        SELECT T1.ID, T1.Category, 
               CASE ID
                  WHEN 4 THEN 1
                  WHEN 3 THEN 2
                  WHEN 1 THEN 3
                  WHEN 5 THEN 4
                  WHEN 6 THEN 5
               END AS query_name_here_sort_order
          FROM CATEGORIES AS T1
       ) AS T2 (
                ID, Category, 
                query_name_here_sort_order
               )
 ORDER 
    BY query_name_here_sort_order;

If the sort order is used by multiple queries and/or applications then add it to a column in a table in the database then use that column in your query.

onedaywhen