Order by selected record in MySQL?

MySQLMySQLi Database

You can use a CASE statement for this. Let us first create a table −

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

Insert records in the table using insert command −

mysql> insert into DemoTable values(490);
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable values(310);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(540);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(123);
Query OK, 1 row affected (0.60 sec)
mysql> insert into DemoTable values(1230);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(1090);
Query OK, 1 row affected (0.43 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select * from DemoTable;

This will produce the following output −

+--------+
| Number |
+--------+
| 490    |
| 310    |
| 540    |
| 123    |
| 1230   |
| 1090   |
+--------+
6 rows in set (0.00 sec)

Following is the query to order by selected record in MySQL −

mysql> select *from DemoTable
order by (case when Number = 1090 then 0 else 1 end), Number;

This will produce the following output −

+--------+
| Number |
+--------+
| 1090   |
| 123    |
| 310    |
| 490    |
| 540    |
| 1230   |
+--------+
6 rows in set (0.00 sec)
raja
Published on 03-May-2019 10:56:08
Advertisements