SQL ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns.
- We can use the keyword DESC to sort the data in descending order.
- And the keyword ASC to sort in ascending order.
ORDER BY Syntax
SELECT * FROM table_name
ORDER BY column_name1, column_name2,... ASC|DESC;
Sort according to multiple columns
SELECT * FROM table_name
ORDER BY column_name1 ASC|DESC, column_name2,... ASC|DESC;
Student Table
A table of student records, the name of table is "Student", and the name of columns are [ROLL_NO, STUDENT_NAME, ADDRESS, MOBILE_NO, AGE, and BRANCH]:
ROLL_NO |
STUDENT_NAME |
ADDRESS |
MOBILE_NO |
AGE |
BRANCH |
1 |
Mohit Sharma |
Delhi |
XXXXXXXX87 |
20 |
IT |
2 |
Pooja Pandit |
Kolkata |
XXXXXXXX34 |
18 |
CSE |
3 |
Priya Pandey |
Delhi |
XXXXXXXX62 |
19 |
EEE |
4 |
Mohit Kumar Jha |
Allahabad U.P |
XXXXXXXX87 |
20 |
ECE |
5 |
Shevani Shree |
Noida U.P |
XXXXXXXX51 |
17 |
IT |
6 |
Badshah |
Mumbai |
XXXXXXXX02 |
20 |
Civil |
7 |
Viki Mohan |
Pune |
XXXXXXXX72 |
19 |
CSE |
8 |
Sona Kaur |
Indor M.P |
XXXXXXXX81 |
22 |
ME |
ORDER BY Example
ORDER BY DESC
SELECT * FROM Student
ORDER BY Age DESC;
OrderBy DESC, Age from Student Table
ROLL_NO |
STUDENT_NAME |
ADDRESS |
MOBILE_NO |
AGE |
BRANCH |
8 |
Sona Kaur |
Indor M.P |
XXXXXXXX81 |
22 |
ME |
1 |
Mohit Sharma |
Delhi |
XXXXXXXX87 |
20 |
IT |
4 |
Mohit Kumar Jha |
Allahabad U.P |
XXXXXXXX87 |
20 |
ECE |
6 |
Badshah |
Mumbai |
XXXXXXXX02 |
20 |
Civil |
3 |
Priya Pandey |
Delhi |
XXXXXXXX62 |
19 |
EEE |
7 |
Viki Mohan |
Pune |
XXXXXXXX72 |
19 |
CSE |
2 |
Pooja Pandit |
Kolkata |
XXXXXXXX34 |
18 |
CSE |
5 |
Shevani Shree |
Noida U.P |
XXXXXXXX51 |
17 |
IT |
ORDER BY Multiple Columns
SQL statement selects all Students from the "Student" table, sorted by the "Student_Name" and the "Age" column. That means it orders by Student_Name, but if some rows have the same Student_Name, it orders them by Age;
SELECT * FROM Student
ORDER BY Student_Name, Age;
Result OrderBy Multple Columns
Roll_No |
Student_Name |
Address |
Mobile_No |
Age |
Branch |
6 |
Badshah |
Mumbai |
XXXXXXXX02 |
20 |
Civil |
1 |
Mohit Sharma |
Delhi |
XXXXXXXX87 |
20 |
IT |
4 |
Mohit Kumar Jha |
Allahabad U.P |
XXXXXXXX87 |
20 |
ECE |
2 |
Pooja Pandit |
Kolkata |
XXXXXXXX34 |
18 |
CSE |
3 |
Priya Pandey |
Delhi |
XXXXXXXX62 |
19 |
EEE |
5 |
Shevani Shree |
Noida U.P |
XXXXXXXX51 |
17 |
IT |
8 |
Sona Kaur |
Indor M.P |
XXXXXXXX81 |
22 |
ME |
7 |
Viki Mohan |
Pune |
XXXXXXXX72 |
19 |
CSE |
ORDER BY Multiple Columns ASC|DESC
SELECT * FROM Student
ORDER BY Student_Name ASC, Age DESC;