TRENDING TOPICS

×

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, then it orders 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;

Advertise With Us

We offer sponsored posts and guest posts with do-follow links, back-links, and other advertising services, To advertise email us at "advertise@gdatamart.com"

© 2021 GDATAMART.COM (All Rights Reserved)