SQL ORDER BY keyword

SQL “Order by” statement is used for sorting table records either in the ascending or in the descending order at the time of retrieval.

SQL ORDER BY Syntax

Select column1, column2,... columnN from table_name order by column1 ASC|DESC;

Above we have specified sorting on column1. Here, ASC is used for sorting in ascending order whereas DESC is used for sorting in descending order. If any sorting option is not specified, then the default sorting will be done in ascending order.


Sample Table

Employee

IDNAMESALARYADDRESSDESIGNATIONAGE
1Peter Clark90000.00Daphne Road ManukauManager36
2Alfredo Smith60000.00Pimpama Drive RotoruaPrincipal Engineer32
3James Cook40500.00Saint-Antoine QuebecSDE I27
4Hudson Stewart45000.00Stoney Creek OntarioSDE II30
5Nathan Taylor55000.00Long Street, WoolstonSDE II31

Example

  • Fetching table records in ascending order of salary
SELECT * FROM Employee ORDER BY Salary;
IDNAMESALARYADDRESSDESIGNATIONAGE
3James Cook40500.00Saint-Antoine QuebecSDE I27
4Hudson Stewart45000.00Stoney Creek OntarioSDE II30
5Nathan Taylor55000.00Long Street, WoolstonSDE II31
2Alfredo Smith60000.00Pimpama Drive RotoruaPrincipal Engineer32
1Peter Clark90000.00Daphne Road ManukauManager36

  • SQL ORDER BY query to fetch records in descending order of salary
SELECT * FROM Employee ORDER BY Salary DESC;

ORDER BY On Multi Columns

There will be instances when we need to apply sort on more than one column. In that case, we will need to define a multi-column sort order separated by a comma.

Syntax

Select * from table_name order by column1 ASC, column2 DESC;

Example

Fetching table records sorted on designation and salary. This means records will be sorted on designation first, and if designation matches, then the sorting will be done on salary.

SELECT * FROM Employee ORDER BY Designation ASC,Salary ASC;

This is all about the “Order By” statement in SQL.

Hope you liked the article. If you have any doubts or concerns, please feel free to write us in comments or mail us at admin@codekru.com

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *