How can we sort multiple columns in a single query?


We can sort multiple columns in a single query by giving more than one column name with ORDER BY Clause. The syntax of the above is as follows −

Syntax

Select Col1,Col2,… from table_name ORDER BY Col1, Col2,…

Example

Suppose we want to sort the table named ‘Student’ by columns ‘Name’ and ‘RollNo’ both then we can write the single query for this as follows −

mysql> Select Name, RollNo from student order by name,rollno;
+--------+--------+
| name   | rollno |
+--------+--------+
| Aarav  |    150 |
| Aryan  |    165 |
| Gaurav |    100 |
+--------+--------+
3 rows in set (0.00 sec)

The above query gave ‘Name’ and ‘Rollno’ as the sorted output. We can also get all the columns of the table as output as follows −

mysql> Select * from student order by name,rollno;
+--------+--------+--------+
| Name   | RollNo | Grade  |
+--------+--------+--------+
| Aarav  |    150 | M.SC   |
| Aryan  |    165 | M.tech |
| Gaurav |    100 | B.tech |
+--------+--------+--------+
3 rows in set (0.00 sec)

Updated on: 22-Jun-2020

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements