Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I avoid too many OR statements in a MySQL query?
Use MySQL IN() to avoid too many OR statements. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(40) ); Query OK, 0 rows affected (0.89 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+ | Id | Name | +----+--------+ | 1 | Chris | | 2 | Robert | | 3 | Mike | | 4 | Sam | | 5 | David | +----+--------+ 5 rows in set (0.00 sec)
Following is the query to avoid too many OR statements in a MySQL query i.e. using IN() −
mysql> select *from DemoTable where Id IN(1,3,5);
This will produce the following output −
+----+-------+ | Id | Name | +----+-------+ | 1 | Chris | | 3 | Mike | | 5 | David | +----+-------+ 3 rows in set (0.00 sec)
Advertisements
