- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Display IDs in a particular order with MySQL IN()?
To display IDs in a particular order i.e. the order of your choice use FIELD() method.
Let us first create a table −
mysql> create table DemoTable ( UserId int ); Query OK, 0 rows affected (0.64 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(80); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(70); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(60); Query OK, 1 row affected (0.13 sec)
Following is the query to display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output
+--------+ | UserId | +--------+ | 100 | | 10 | | 40 | | 80 | | 70 | | 60 | +--------+ 6 rows in set (0.00 sec)
Following is the query to use IN() and FIELD() to display records in the order of your choice −
mysql> select UserId from DemoTable where UserId IN(60,100,10,80,40,70) order by field(UserId,60,100,10,80,40,70);
This will produce the following output −
+--------+ | UserId | +--------+ | 60 | | 100 | | 10 | | 80 | | 40 | | 70 | +--------+ 6 rows in set (0.03 sec)
Advertisements