MySQL - SELECT … WHERE id IN (..) order with particular column?


You can SELECT ….WHERE id IN(..) using field() function to order with any column. The syntax is as follows −

SELECT *FROM yourTableName WHERE yourColumnName IN(‘value1’,’value2’,.......N)
ORDER BY FIELD(yourColumnName,value1’,’value2’,.......N);

To understand the above syntax, let us create a table −

mysql> create table SelectOrderbyField
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(30),
   -> Age int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into SelectOrderbyField(Name,Age) values('John',23);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SelectOrderbyField(Name,Age) values('Carol',25);
Query OK, 1 row affected (0.16 sec)

mysql> insert into SelectOrderbyField(Name,Age) values('Bob',21);
Query OK, 1 row affected (0.15 sec)

mysql> insert into SelectOrderbyField(Name,Age) values('Mike',28);
Query OK, 1 row affected (0.17 sec)

mysql> insert into SelectOrderbyField(Name,Age) values('Sam',26);
Query OK, 1 row affected (0.12 sec)

mysql> insert into SelectOrderbyField(Name,Age) values('David',23);
Query OK, 1 row affected (0.19 sec)

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

mysql> select *from SelectOrderbyField;

The following is the output −

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | John  |   23 |
|  2 | Carol |   25 |
|  3 | Bob   |   21 |
|  4 | Mike  |   28 |
|  5 | Sam   |   26 |
|  6 | David | 23   |
+----+-------+------+
6 rows in set (0.00 sec)

Here are the queries to select ...where id in(..) using order by field() function.

Order with ID column

The query is as follows −

mysql> select *from SelectOrderbyField where Id IN(5,1,3,2,6,4)
   -> order by field(Id,5,1,3,2,6,4);

The following is the output −

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  5 | Sam   |   26 |
|  1 | John  |   23 |
|  3 | Bob   |   21 |
|  2 | Carol |   25 |
|  6 | David |   23 |
|  4 | Mike  | 28   |
+----+-------+------+
6 rows in set (0.00 sec)

Order with Name column

You can correctly order on the basis of Name column. The query is as follows −

mysql> select *from SelectOrderbyField where Name IN('Sam','John','Bob','Carol','David','Mike')
   -> order by field(Name,'Sam','John','Bob','Carol','David','Mike');

The following is the output −

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 5  | Sam   | 26   |
| 1  | John  | 23   |
| 3  | Bob   | 21   |
| 2  | Carol | 25   |
| 6  | David | 23   |
| 4  | Mike  | 28   |
+----+-------+------+
6 rows in set (0.03 sec)

Updated on: 30-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements