- 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
Implement MySQL query using multiple OR statements. Any optimal alternative?
It would be good to use IN() instead of multiple OR statements. Let us first create a table −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstName varchar(20) -> ); Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FirstName) values('John'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(FirstName) values('Adam'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable(FirstName) values('David'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(FirstName) values('Mike'); Query OK, 1 row affected (0.48 sec) mysql> insert into DemoTable(FirstName) values('Bob'); Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Adam | | 3 | David | | 4 | Mike | | 5 | Bob | +----+-----------+ 5 rows in set (0.00 sec)
Here is the query for using IN() −
mysql> select *from DemoTable where Id IN(2,3,5);
This will produce the following output −
+----+-----------+ | Id | FirstName | +----+-----------+ | 2 | Adam | | 3 | David | | 5 | Bob | +----+-----------+ 3 rows in set (0.00 sec)
Advertisements