coderz.py

Keep Coding Keep Cheering!

SQL: ORDER BY Clause

SQL Views
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:

IDNAMEAGEADDRESSSALARY
2Shiva Tiwari22Bhopal21000
3Ajeet Bhargav45Meerut65000
4Ritesh Yadav36Azamgarh26000
5Balwant Singh45Varanasi36000
6Mahesh Sharma26Mathura22000
  • 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:

IDNAMEAGEADDRESSSALARY
3Ajeet Bhargav45Meerut65000
5Balwant Singh45Varanasi36000
4Ritesh Yadav36Azamgarh26000
6Mahesh Sharma26Mathura22000
2Shiva Tiwari22Bhopal21000
  • 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:

IDNAMEAGEADDRESSSALARY
5Balwant Singh45Varanasi36000
3Ajeet Bhargav45Meerut65000
4Ritesh Yadav36Azamgarh26000
6Mahesh Sharma26Mathura22000
2Shiva Tiwari22Bhopal21000

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

Leave a Comment

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

Advertisement