Sunday 3 January 2016

ORDER BY clause in SQL

ORDER BY clause in SQL is used for sorting the data either in ascending or descending order based on a specified condition.
ORDER BY clause syntax:
SELECT column-list FROM table_name [WHERE condition-optional] [ORDER BY column1, column2, .. columnN] [ASC |DESC];
Example-ORDER BY clause on single column:
Select * from BANK ORDER BY Salary ASC
Select Count (*) from EMP WHERE Job=’Clerk’ ORDER BY Salary ASC
Example-ORDER BY clause on multiple columns:
Select * from BANK ORDER BY Salary, CustomerId DESC
In the above query, if the two customers have the same salary then only it goes to CustomerId for ordering the data otherwise only ORDER BY salary is performed.
Note:
  1. The ORDER BY clause sorts the records in ascending order by default
  2. We can use the Ascending and Descending sorting criteria individually or in combination as well
Select * from BANK ORDER BY Salary DESC, CustomerId ASC

No comments:

Post a Comment