SQL ORDER BY Clause
The ORDER BY Clause is used to sort the records in ascending or descending order, based on one or more columns.
Mostly all database server query fetch records by default in ascending order.
The Syntax of ORDER BY Clause :
For ascending order :
SELECT col1, col2 FROM tableName ORDER BY col1 ASC
For descending order :
SELECT col1, col2 FROM tableName ORDER BY col1 DESC
Example of how to use ORDER BY Clause
SELECT * FROM Student ORDER BY LastName
OR
SELECT * FROM Student ORDER BY LastName ASC
SELECT * FROM Student ORDER BY LastName DESC
Here, we can understand ORDER BY Clase with sql table “StudentMst”
SELECT * FROM StudentMst
ID | Name | City | Pincode | Mobile |
---|---|---|---|---|
1 | Meera | Bombay | 380022 | 7874555555 |
2 | Rahul | Surat | 352200 | 7874444444 |
3 | Jayesh | Ahmedabad | 352200 | 7874333333 |
4 | Dhvanish | Bombay | 380022 | 7874111111 |
5 | Reena | Baroda | 352222 | 7874666666 |
6 | Veera | Baroda | 352222 | 7874121212 |
SELECT * FROM StudentMst ORDER BY City
ID | Name | City | Pincode | Mobile |
---|---|---|---|---|
3 | Jayesh | Ahmedabad | 352200 | 7874333333 |
5 | Reena | Baroda | 352222 | 7874666666 |
6 | Veera | Baroda | 352222 | 7874121212 |
4 | Dhvanish | Bombay | 380022 | 7874111111 |
1 | Meera | Bombay | 380022 | 7874555555 |
2 | Rahul | Surat | 352200 | 7874444444 |
SELECT * FROM StudentMst ORDER BY City DESC
ID | Name | City | Pincode | Mobile |
---|---|---|---|---|
2 | Rahul | Surat | 352200 | 7874444444 |
4 | Dhvanish | Bombay | 380022 | 7874111111 |
1 | Meera | Bombay | 380022 | 7874555555 |
5 | Reena | Baroda | 352222 | 7874666666 |
6 | Veera | Baroda | 352222 | 7874121212 |
3 | Jayesh | Ahmedabad | 352200 | 7874333333 |
SELECT * FROM StudentMst ORDER BY Name ASC
ID | Name | City | Pincode | Mobile |
---|---|---|---|---|
4 | Dhvanish | Bombay | 380022 | 7874111111 |
3 | Jayesh | Ahmedabad | 352200 | 7874333333 |
1 | Meera | Bombay | 380022 | 7874555555 |
2 | Rahul | Surat | 352200 | 7874444444 |
5 | Reena | Baroda | 352222 | 7874666666 |
6 | Veera | Baroda | 352222 | 7874121212 |