Can we return query results in same order as the values in MySQL `IN(…)` statement?


Yes, you can achieve this with ORDER BY FIELD() from MySQL. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(19);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(34);
Query OK, 1 row affected (0.32 sec)

mysql> insert into DemoTable values(28);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values(25);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values(29);
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values(24);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| Number |
+--------+
|     19 |
|     30 |
|     34 |
|     28 |
|     25 |
|     29 |
|     24 |
+--------+
7 rows in set (0.00 sec)

Following is the query to return result in the same order as the values set −

mysql> select *from DemoTable
   -> ORDER BY FIELD(Number, 30,19,34,25,28,29,24) ;

This will produce the following output displaying the results in the same order −

+--------+
| Number |
+--------+
|     30 |
|     19 |
|     34 |
|     25 |
|     28 |
|     29 |
|     24 |
+--------+
7 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements