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: 2020-06-22T08:36:05+05:30

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements