How to get MySQL query result in same order as given by IN clause?


For this, you can use IN() along with ORDER BY FIELD(). Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Sam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName) values('Carol');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.42 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Chris     |
|  2 | Robert    |
|  3 | Mike      |
|  4 | Sam       |
|  5 | Carol     |
|  6 | David     |
+----+-----------+
6 rows in set (0.00 sec)

The following is how to get query results in the same order as given by the IN clause.

mysql> select FirstName from DemoTable where Id IN(4,5,6) order by field(Id,4,5,6);

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| Sam       |
| Carol     |
| David     |
+-----------+
3 rows in set (0.00 sec)

Updated on: 26-Sep-2019

915 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements