Select with set order in MySQL

MySQLMySQLi Database

For this, you need to use IN() and after that FIELD() method. Let us first create a table −

mysql> create table DemoTable(
   StudentId varchar(10),
   StudentName varchar(20)
) ;
Query OK, 0 rows affected (4.11 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('10001','Adam');
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable values('1010','Chris');
Query OK, 1 row affected (0.72 sec)
mysql> insert into DemoTable values('1020','Bob');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable values('1030','Carol');
Query OK, 1 row affected (0.47 sec)
mysql> insert into DemoTable values('1040','Sam');
Query OK, 1 row affected (0.29 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 10001     | Adam        |
| 1010      | Chris       |
| 1020      | Bob         |
| 1030      | Carol       |
| 1040      | Sam         |
+-----------+-------------+
5 rows in set (0.00 sec)

Following is the query to select with set order in MySQL −

mysql> select *from DemoTable
where StudentId IN('1040','1010','1020','1030','10001')
order by FIELD(StudentId,'1040','1010','1020','1030','10001');

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1040      | Sam         |
| 1010      | Chris       |
| 1020      | Bob         |
| 1030      | Carol       |
| 10001     | Adam        |
+-----------+-------------+
5 rows in set (0.02 sec)
raja
Published on 27-Sep-2019 07:43:16
Advertisements