February 26, 2014

SQL ORDER BY clause

We all know that order by keyword is used to sort the output of the query either in ascending or descending order. By default, order by keyword sorts the result in ascending order. In order to sort the result in descending order all we need to use is "desc" keyword.

Ascending Order Example:

select column_a from table order by column_a

Result:
coloumn_a
1
2
3
4
5

Descending Order Example:

select column_a from table order by column_a desc

Result:
column_a
5
4
3
2
1

Manipulating Order By keyword:

Above, we have seen an example how to sort the specified column in an ascending or descending order. But, in the real world projects we face such situation where we have to sort in the specific way. Let's take above example. If we would like to see number 3 of column_a always on the top of the result. Then ,

select column_a from table
order by case when column_a = '3' then '1' else column_a end asc

Result:
column_a
3
1
2
4
5

No comments: