How can I get the records from MySQL table in result set in a particular way?


For getting the records from MySQL table in the result set in a particular way either ascending or descending, we need to use the ORDER BY clause along with ASC or DESC keywords. If we will not use any of the above-mentioned keywords then MySQL by default return the records in ascending order. The ORDER BY clause returned the result set based on a particular field (ascending or descending order) with which we will use the ORDER BY clause. Suppose we want to sort the rows of the following table −

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

The query below sorted the table by ‘Name’ in ASCENDING order.

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

The query below sorted the table by ‘Grade in DESCENDING order.

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

Updated on: 22-Jun-2020

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements