;

SQL ORDER BY


In this tutorial, we will learn how to use ORDER BY Keyword to select records in ascending or descending order.

SQL ORDER BY Keyword

  • ORDER BY keyword is used to sort the records in ascending or descending order.
  • By Default, ORDER BY keyword sorts the records in ascending order.
  • To sort the record in descending order, DESC keyword is used.
Syntax - ORDER BY Keyword
SELECT column1, column2,...columnN
FROM tableName
ORDER BY column1, column2,...ASC|DESC;

Example:

Let us consider this table "Employee" for records.

Table Name: Employee

ID EmpName City Country Gender Salary
1 Shankar Delhi India male 25000
2 Sourabh Delhi India male 30000
3 Ranvijay Mumbai India male 15000
4 Kapil Noida India male 25000
5 Shalini Jaipur India female 18000
6 Rakesh Faridabad India male 23000
7 Akshay Mumbai India male 21000
8 Sarah New York US female 76000
9 Rocky Noida India male 28000

ORDER BY Ascending

For selecting a salary by ascending, a query will be:

Example - ORDER BY Ascending
SELECT *
FROM Employee 
ORDER BY SALARY ASC
Output - ORDER BY Ascending
ID EmpName City Country Gender Salary
3 Ranvijay Mumbai India male 15000
5 Shalini Jaipur India female 18000
7 Akshay Mumbai India male 21000
6 Rakesh Faridabad India male 23000
4 Kapil Noida India male 25000
1 Shankar Delhi India male 25000
9 Rocky Noida India male 28000
2 Sourabh Delhi India male 30000
8 Sarah New York US female 76000

ORDER BY Descending

For selecting a salary by descending, a query will be:-

Example - ORDER BY Descending
SELECT *
FROM Employee 
ORDER BY SALARY DESC
Output - ORDER BY Descending
ID EmpName City Country Gender Salary
8 Sarah New York US female 76000
2 Sourabh Delhi India male 30000
9 Rocky Noida India male 28000
4 Kapil Noida India male 25000
1 Shankar Delhi India male 25000
6 Rakesh Faridabad India male 23000
7 Akshay Mumbai India male 21000
8 Shalini Jaipur India female 18000
9 Ranvijay Mumbai India male 15000

ORDER BY on multiple columns

For selecting multiple columns, one in ascending order and others in descending order, a query will be:

Example - ORDER BY on multiple columns
SELECT *
FROM Employee 
ORDER BY City ASC,EmpName DESC;
Output - ORDER BY on multiple columns
ID EmpName City Country Gender Salary
4 Kapil Noida India male 25000
9 Rocky Noida India male 28000
8 Sarah New York US female 76000
7 Akshay Mumbai India male 21000
3 Ranvijay Mumbai India male 15000
5 Shalini Jaipur India female 18000
6 Rakesh Faridabad India male 23000
1 Shankar Delhi India male 25000
2 Sourabh Delhi India male 30000