Display IDs in a particular order with MySQL IN()?


To display IDs in a particular order i.e. the order of your choice use FIELD() method.

Let us first create a table −

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

Following is the query to insert some records in the table using insert command −

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.13 sec)

Following is the query to display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output

+--------+
| UserId |
+--------+
| 100    |
| 10     |
| 40     |
| 80     |
| 70     |
| 60     |
+--------+
6 rows in set (0.00 sec)

Following is the query to use IN() and FIELD() to display records in the order of your choice −

mysql> select UserId from DemoTable where UserId IN(60,100,10,80,40,70)
order by field(UserId,60,100,10,80,40,70);

This will produce the following output −

+--------+
| UserId |
+--------+
| 60     |
| 100    |
| 10     |
| 80     |
| 40     |
| 70     |
+--------+
6 rows in set (0.03 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements