How to sort MySQL output on the basis of the column which is not in the result set?

MySQLMySQLi Database

It is quite possible to get the sorted output on the basis of the column which is not even the part of that output or not in the result set. It can be done by selecting the required fields and writing the name of the fields on the basis of which sorting order is desired. Following is an example to demonstrate it, in which we sorted out the result set, having ‘Name’ and ‘Address’ fields, on the basis of column ‘id’.

mysql> Select Name, Subject From Student ORDER BY Id;
+---------+-----------+
| Name    | Subject   |
+---------+-----------+
| Gaurav  | Computers |
| Aarav   | History   |
| Harshit | Commerce  |
| Raman   | Computers |
+---------+-----------+
4 rows in set (0.00 sec)

We can also use DESC or ASC keywords as follows

mysql> Select Name, Subject from Student ORDER BY Id DESC;
+---------+-----------+
| Name    | Subject   |
+---------+-----------+
| Raman   | Computers |
| Harshit | Commerce  |
| Aarav   | History   |
| Gaurav  | Computers |
+---------+-----------+
4 rows in set (0.00 sec)
raja
Published on 19-Feb-2018 11:13:38
Advertisements