What is the ORDER BY Clause?
- In the SELECT query, the ORDER BY clause can be used to sort the result in ascending or descending order of one or more columns.
- ORDER BY by default sorts the data in ascending order.
- We can sort the data in descending order with the keyword DESC and ascending order with the keyword ASC.
Syntax :
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
Note: In the ORDER BY clause, multiple columns are allowed. One needs to ensure that the column used to sort the data should be in the column-list.
Example:
Consider Employee table:
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
2 | Shiva Tiwari | 22 | Bhopal | 21000 |
3 | Ajeet Bhargav | 45 | Meerut | 65000 |
4 | Ritesh Yadav | 36 | Azamgarh | 26000 |
5 | Balwant Singh | 45 | Varanasi | 36000 |
6 | Mahesh Sharma | 26 | Mathura | 22000 |
- Sort according to a single column:
SELECT * FROM Employee ORDER BY AGE DESC;
The above query will return the resultant data in descending order of the AGE.
Output:
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
3 | Ajeet Bhargav | 45 | Meerut | 65000 |
5 | Balwant Singh | 45 | Varanasi | 36000 |
4 | Ritesh Yadav | 36 | Azamgarh | 26000 |
6 | Mahesh Sharma | 26 | Mathura | 22000 |
2 | Shiva Tiwari | 22 | Bhopal | 21000 |
- Sort according to multiple columns:
SELECT * FROM Employee ORDER BY Age DESC, SALARY ASC;
The query above will retrieve all data from the table Employee and then sort the results in descending order first by the column Age and then in ascending order by the column SALARY.
Output:
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
5 | Balwant Singh | 45 | Varanasi | 36000 |
3 | Ajeet Bhargav | 45 | Meerut | 65000 |
4 | Ritesh Yadav | 36 | Azamgarh | 26000 |
6 | Mahesh Sharma | 26 | Mathura | 22000 |
2 | Shiva Tiwari | 22 | Bhopal | 21000 |
In the above output, we can see that the results are sorted in descending order by Age. There are several rows with the same Age. Now, sorting this result-set further by SALARY will sort the rows with the same Age by SALARY in ascending order.
Note: also read about SQL: LIKE clause
Follow Me
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment