Implement WHERE IN vs OR in MySQL with similar example


The IN uses an index while OR does not use an index in MySQL.

Let us first create a table −

mysql> create table DemoTable711 (
   Id int,
   Name varchar(100)
);
Query OK, 0 rows affected (0.92 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable711 values(100,'Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable711 values(101,'Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable711 values(102,'Carol');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable711 values(103,'Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable711 values(104,'Sam');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable711;

This will produce the following output -

+------+--------+
| Id   | Name   |
+------+--------+
| 100  | Chris  |
| 101  | Robert |
| 102  | Carol  |
| 103  | Mike   |
| 104  | Sam    |
+------+--------+
5 rows in set (0.00 sec)

Following is the query for IN() method −

mysql> select *from DemoTable711 where Id IN(101,103,104);

This will produce the following output -

+------+--------+
| Id   | Name   |
+------+--------+
| 101  | Robert |
| 103  | Mike   |
| 104  | Sam    |
+------+--------+
3 rows in set (0.03 sec)

Following is the query for OR −

mysql> select *from DemoTable711 where Id=101 OR Id=103 OR Id=104;

This will produce the following output -

+------+--------+
| Id   | Name   |
+------+--------+
| 101  | Robert |
| 103  | Mike   |
| 104  | Sam    |
+------+--------+
3 rows in set (0.00 sec)

Updated on: 22-Aug-2019

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements