How to make MySQL result set the same as specified?


For this, use MySQL FIND_IN_SET(). Let us first create a table −

mysql> create table DemoTable1563
   -> (
   -> StudentId int,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1563 values(1001,'Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1563 values(1010,'Bob');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1563 values(1005,'Chris');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1563 values(1015,'David');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1563 values(1030,'Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1563 values(1020,'Sam');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1563;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|      1001 | Chris       |
|      1010 | Bob         |
|      1005 | Chris       |
|      1015 | David       |
|      1030 | Mike        |
|      1020 | Sam         |
+-----------+-------------+
6 rows in set (0.00 sec)

Here is the query to form MySQL result set the same as specified −

mysql> select * from DemoTable1563
   -> where StudentId IN(1001,1030,1010,1020)
   -> order by find_in_set(StudentId,'1001,1030,1010,1020');

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|      1001 | Chris       |
|      1030 | Mike        |
|      1010 | Bob         |
|      1020 | Sam         |
+-----------+-------------+
4 rows in set (0.00 sec)

Updated on: 12-Dec-2019

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements