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.
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…
Problem Statement (Asked By Airbnb) Given a list of integers, write a function to compute…