Syntax error Get the returned record set ordered by (ORDER BY) position in MySQL 'IN' clause

Get the returned record set ordered by (ORDER BY) position in MySQL 'IN' clause



To return record set order, you need to use FIND_IN_SET(). Let us first create a table −

mysql> create table recordSetOrderDemo
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(30)
   -> );
Query OK, 0 rows affected (0.63 sec)

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

mysql> insert into recordSetOrderDemo values(20,"John");
Query OK, 1 row affected (0.20 sec)

mysql> insert into recordSetOrderDemo values(10,"Larry");
Query OK, 1 row affected (0.14 sec)

mysql> insert into recordSetOrderDemo values(100,"Mike");
Query OK, 1 row affected (0.14 sec)

mysql> insert into recordSetOrderDemo values(50,"Sam");
Query OK, 1 row affected (0.11 sec)

mysql> insert into recordSetOrderDemo values(10,"David");
Query OK, 1 row affected (0.18 sec)

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

mysql> select *from recordSetOrderDemo;

This will produce the following output −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
| 20         | John         |
| 10         | Larry        |
| 100        | Mike         |
| 50         | Sam          |
| 10         | David        |
+------------+--------------+
5 rows in set (0.00 sec)

Following is the query to return record set order −

mysql> select *from recordSetOrderDemo where EmployeeId IN(100,10,20,50)
-> ORDER BY FIND_IN_SET(EmployeeId,'100,10,20,50');

This will produce the following output −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
| 100        | Mike         |
| 10         | Larry        |
| 10         | David        |
| 20         | John         |
| 50         | Sam          |
+------------+--------------+
5 rows in set (0.03 sec)
Updated on: 2019-07-30T22:30:25+05:30

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements