Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom order in SQL

We are querying database to retrieve data in following fashion

select a,b,...f from table1 where id in (6,33,1,78,2)

The result I got from query is in following order 1,2,6,33,78.

I want the result in same order (6,33,1,78,2). Is there any way to retrieve the data in same order.

EDIT *I am using SQL 2008*

like image 374
Ram Avatar asked Apr 20 '12 11:04

Ram


People also ask

How do I create a custom order in SQL?

By default SQL ORDER BY sort, the column in ascending order but when the descending order is needed ORDER BY DESC can be used. In case when we need a custom sort then we need to use a CASE statement where we have to mention the priorities to get the column sorted.

How do I specify an 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 customized sorting?

When lists of values are displayed in an application page, a user can sort the list by clicking on the column headers. The sort order of the rows will be determined by the sort order of the values in the selected column.

What is SQL ORDER BY 1?

it simply means sorting the view or table by 1st column of the query's result.


2 Answers

add this order by clause

order by case 
         when id = 6 then 1 
         when id = 33 then 2  
         when id = 1 then 3  
         when id = 78 then 4  
         when id = 2 then 5  
      end

If using MySQL you can do this

ORDER BY FIND_IN_SET(id, '6,33,1,78,2')
like image 106
juergen d Avatar answered Sep 21 '22 22:09

juergen d


Using a Table Value Constructor:

SELECT a, b, ... f 
FROM 
        table1 
    JOIN
        ( VALUES 
            (1,  6), 
            (2, 33), 
            (3,  1), 
            (4, 78), 
            (5,  2) 
        ) AS ordering (position, id)
      ON  ordering.id = table1.id
ORDER BY position 
like image 32
ypercubeᵀᴹ Avatar answered Sep 18 '22 22:09

ypercubeᵀᴹ