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.
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 |
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 |
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
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…