Order by a single field and display rest of the records in the same order with MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.82 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(201,'Chris Brown');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(110,'John Doe');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values(101,'Adam Smith');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(345,'Carol Taylor');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(135,'John Smith');
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 −

+------+--------------+
| Id   | Name         |
+------+--------------+
|  201 | Chris Brown  |
|  110 | John Doe     |
|  101 | Adam Smith   |
|  345 | Carol Taylor |
|  135 | John Smith   |
+------+--------------+
5 rows in set (0.00 sec)

Here is the query to ORDER By field. The Id 101 would remain on the top and rest of the records would get displayed in the same order −

mysql> select *from DemoTable
   -> order by (Id=101) desc;

This will produce the following output −

+------+--------------+
| Id   | Name         |
+------+--------------+
| 101  | Adam Smith   |
| 201  | Chris Brown  |
| 110  | John Doe     |
| 345  | Carol Taylor |
| 135  | John Smith   |
+------+--------------+
5 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 07:43:54
Advertisements