In this tutorial, you will learn how to sort the result set on multiple columns using the SQL ORDER BY clause.
Sometimes we may need to sort the result set on more than one column.
Syntax
The syntax for sorting result set on multiple columns is as below.
SELECT expressions FROM tables ORDER BY column1 [ ASC | DESC], column2 [ ASC | DESC], ...., columnN [ ASC | DESC];
Example
Suppose we have an Employee
table in our database with the following data.
ID | NAME | GENDER | AGE | SALARY |
1510 | Avinash | M | 35 | 33000 |
1511 | Ramjan | M | 31 | 56000 |
1512 | Priyanka | F | 32 | 42000 |
1513 | Priyam | M | 25 | 42000 |
1514 | Jitu | M | 23 | 43000 |
1515 | Raman | M | 26 | 49000 |
1516 | Lata | F | 25 | 27000 |
1517 | Prakash | M | 38 | 45000 |
1518 | Nitu | F | 40 | 45000 |
1519 | Pallab | M | 33 | 42000 |
1520 | Pankaj | M | 39 | 55000 |
Now let’s display all information for each employee sorted by the first Salary
in descending order and then by Name
in ascending order.
SELECT * FROM Employee ORDER BY SALARY DESC, NAME;
ID | NAME | GENDER | AGE | SALARY |
1511 | Ramjan | M | 31 | 56000 |
1520 | Pankaj | M | 39 | 55000 |
1515 | Raman | M | 26 | 49000 |
1517 | Prakash | M | 38 | 45000 |
1518 | Nitu | F | 40 | 45000 |
1514 | Jitu | M | 23 | 43000 |
1519 | Pallab | M | 33 | 42000 |
1513 | Priyam | M | 25 | 42000 |
1512 | Priyanka | F | 32 | 42000 |
1510 | Avinash | M | 35 | 33000 |
1516 | Lata | F | 25 | 27000 |
In the above example, records are first sorted by Salary
in descending order and if multiple records exist for the same salary, those records are sorted by Name
in ascending order.