Thursday, September 4, 2008

SQL Order By our specific order


Generally we can get the records in alphabetical or numeric order by default either in ascending or descending by specifying ORDER BY clause in the query. But sometimes in our applications, we may need to get the records in a specific order. For example, the order of names that we get from the database needs to be displayed in an order other than A to Z or Z to A. Here is the solution that i found.

Example:
Suppose that there is a query like below:
select * from emp where empname in ('B1','A1','C1')
You want the records to be displayed in the same order as above. Then change the query as below.

select * from emp
where empname in ('B1','A1','C1')
order by CASE empname
WHEN 'B1' THEN 1
WHEN 'A1' THEN 2
WHEN 'C1' THEN 3

END