SQL ORDER BY

Write SQL Query to sort the result in ascending and descending order

ORDER BY keyword is used to sort the result-set in ascending or descending order

Example


Table: Employee                            
+----+-------+--------+--------------+      
| Id | Name  | Salary | DepartmentId |      
+----+-------+--------+--------------+      
1  | Ram   | 85000  | 1            |      
2  | Henry | 80000  | 2            |    
3  | Sam   | 60000  | 2            |    
4  | Shyam | 60000  | 1            |
5  | Geeta | 90000  | 1            |
6  | Sheet | 90000  | 1            |
7  | Leela | 80000  | 1            |
8  | Geeta | 70000  | 1            |
+----+-------+--------+--------------+

Query: Sort the result based on NAME in ascending order


SELECT NAME EMPNAME, SALARY FROM EMPLOYEE ORDER BY NAME

Result: 

+------------------+
| EMPNAME | SALARY |
+---------+--------+
| Geeta   | 70000  |
| Geeta   | 90000  |
| Henry   | 80000  |
| Leela   | 80000  |
| Ram     | 85000  |
| Sam     | 60000  |
| Sheeta  | 90000  |
| Shyam   | 60000  |
+---------+--------+

Query: Sort the result based on SALARY and NAME in ascending order


SELECT NAME EMPNAME, SALARY FROM EMPLOYEE ORDER BY SALARY, NAME

Result: 

+------------------+
| EMPNAME | SALARY |
+---------+--------+
| Sam     | 60000  |
| Shyam   | 60000  |
| Geeta   | 70000  |
| Henry   | 80000  |
| Leela   | 80000  |
| Ram     | 85000  |
| Geeta   | 90000  |
| Sheeta  | 90000  |
+---------+--------+

Query: Sort the result based on NAME in descending order


SELECT NAME EMPNAME, SALARY FROM EMPLOYEE ORDER BY NAME DESC

Result: 

+------------------+
| EMPNAME | SALARY |
+---------+--------+
| Shyam   | 60000  |
| Sheeta  | 90000  |
| Sam     | 60000  |
| Ram     | 85000  |
| Leela   | 80000  |
| Henry   | 80000  |
| Geeta   | 70000  |
| Geeta   | 90000  |
+---------+--------+


Query: Sort the result based on SALARY and NAME in descending order


SELECT NAME EMPNAME, SALARY 
FROM EMPLOYEE ORDER BY SALARY, NAME DESC

Result: 

+------------------+
| EMPNAME | SALARY |
+---------+--------+
| Shyam   | 60000  |
| Sam     | 60000  |
| Geeta   | 70000  |
| Leela   | 80000  |
| Henry   | 80000  |
| Ram     | 85000  |
| Sheeta  | 90000  |
| Geeta   | 90000  |
+---------+--------+


Query: Sort the result based on SALARY in descending order and NAME in ascending order


SELECT NAME EMPNAME, SALARY FROM EMPLOYEE ORDER BY SALARY DESCNAME ASC

Result: 

+------------------+
| EMPNAME | SALARY |
+---------+--------+
| Geeta   | 90000  |
| Sheeta  | 90000  |
| Ram     | 85000  |
| Henry   | 80000  |
| Leela   | 80000  |
| Geeta   | 70000  |
| Sam     | 60000  |
| Shyam   | 60000  |
+---------+--------+



No comments:

Post a Comment