Friday, November 10, 2006

Oracle Tip - SQL Order by clause with CASE

How to use CASE in ORDER BY clause of SELECT statement in Oracle SQL.
Order By clause allow you display data in ASCENDING or DESCENDING.

Using Order By clause we can able to arrange data in ASCENDING or DESCENDING based on columns. If it is VARCHAR2 column for ASCENDIGN and DESCENDING data will be sorted by Alphabetical. What if we want to sort CUSTOM Sort, not Alphabetically ascending or descending.

For example, take the following SQL. We can display CITY column either in Alphabetically ASC or DESC.

SQL with ORDER BY CITY ASC:
===========================

select city from (
select
'San Francisco' a from dual
union all
Select 'Boston' a from dual
union all
Select 'Charlotte' a from dual
union all
Select 'Phoenix' a from dual
union all
Select 'Houston' a from dual
union all
Select 'Washington DC' a from dual)
order by city ASC

Now let us see how we can do Custom Sorting using CASE clause in ORDER BY Clause.
We want to get list of city in the follwoing order, then we will use the following SQL.

CITY
=====
Charlotte
Boston
Phoenix
Washington DC
Houston
San Francisco


SQL with CUSTOM Sorting.
========================

select city from (
select
'San Francisco' a from dual
union all
Select 'Boston' a from dual
union all
Select 'Charlotte' a from dual
union all
Select 'Phoenix' a from dual
union all
Select 'Houston' a from dual
union all
Select 'Washington DC' a from dual)
order by CASE a when 'Charlotte' then 1
when 'Boston' then 2
when 'Phoenix' then 3
when 'Washington DC' then 4
when 'Houston' then 5
end;


Please note that in CASE clause, I never mentioned about 'San Francisco' city. But the SQL will bring 'San Francisco' as last city in the record set.

This may be required sometimes, we want to display in DropDown List box in frontend applications.

No comments: