Categories: DBMS

SQL: ORDER BY Clause

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

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago