MySQL Order by a specific column x and display remaining values in ascending order

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> MonthNumber int
   -> );
Query OK, 0 rows affected (1.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(9);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(6);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(8);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(5);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+-------------+
| MonthNumber |
+-------------+
|          10 |
|           1 |
|           9 |
|           6 |
|           8 |
|           5 |
+-------------+
6 rows in set (0.00 sec)

Following is the query to order by a specific column and display remaining records in ascending order −

mysql> select * from DemoTable
   -> order by MonthNumber=5 desc,MonthNumber asc;

This will produce the following output −

+-------------+
| MonthNumber |
+-------------+
|           5 |
|           1 |
|           6 |
|           8 |
|           9 |
|          10 |
+-------------+
6 rows in set (0.00 sec)
raja
Published on 17-Dec-2019 10:36:00
Advertisements