How to sort by value with MySQL ORDER BY?


For this, use the ORDER BY clause. Let us first create a table −

mysql> create table DemoTable
   (
   StudentId int
   );
Query OK, 0 rows affected (0.59 sec)

Now you can insert some records in the table using insert command −

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(55);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-----------+
| StudentId |
+-----------+
| 100       |
| 60        |
| 70        |
| 45        |
| 55        |
| 78        |
+-----------+
6 rows in set (0.00 sec)

Following is the query to sort by value with ORDER BY. Here, first we are displaying 70, since we have set its order with ORDER BY. Rest of the ids are displayed in ascending order −

mysql> select *from DemoTable order by StudentId=70 desc,StudentId asc;

Output

+-----------+
| StudentId |
+-----------+
| 70        |
| 45        |
| 55        |
| 60        |
| 78        |
| 100       |
+-----------+
6 rows in set (0.00 sec)
raja
Published on 13-Jun-2019 11:35:49
Advertisements