How to order by a custom rule like order like 4,2,1,3 in MySQL?


To order with a custom rule, use the ORDER BY FIELD(). Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(4);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(2);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(3);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+--------+
| Number |
+--------+
| 1      |
| 4      |
| 2      |
| 3      |
+--------+
4 rows in set (0.00 sec)

Following is the query to ORDER BY custom rule, for example, 4,2,1,3 −

mysql> select *from DemoTable order by field(Number,4,2,1,3);

This will produce the following output with custom ordering −

+--------+
| Number |
+--------+
| 4      |
| 2      |
| 1      |
| 3      |
+--------+
4 rows in set (0.00 sec)
raja
Published on 13-Jun-2019 12:19:17
Advertisements