How can I enhance my select query to make it faster in MySQL?


For quicker querying, use MySQL IN() because it uses indexing internally. Let us first create a table −

mysql> create table DemoTable1618
    -> (
    -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> ClientName varchar(20),
    -> ClientEmailId varchar(30)
    -> );
Query OK, 0 rows affected (1.53 sec)

Insert some records in the table using insert command:

mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('Chris Brown','Brown323@gmail.com');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('David Miller','MillerDavid@gmail.com');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('John Doe','998John_Doe@gmail.com');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('John Smith','999John_Smith@gmail.com');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('Adam Smith','Adam_Smith@gmail.com');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1618;

This will produce the following output −

+----------+--------------+-------------------------+
| ClientId | ClientName   | ClientEmailId           |
+----------+--------------+-------------------------+
|        1 | Chris Brown  | Brown323@gmail.com      |
|        2 | David Miller | MillerDavid@gmail.com   |
|        3 | John Doe     | 998John_Doe@gmail.com   |
|        4 | John Smith   | 999John_Smith@gmail.com |
|        5 | Adam Smith   | Adam_Smith@gmail.com    |
+----------+--------------+-------------------------+
5 rows in set (0.00 sec)

Here is the query to use IN() for faster querying −

mysql> select * from DemoTable1618 where ClientEmailId IN('998John_Doe@gmail.com','999John_Smith@gmail.com','MillerDavid@gmail.com');

This will produce the following output −

+----------+--------------+-------------------------+
| ClientId | ClientName   | ClientEmailId           |
+----------+--------------+-------------------------+
|        2 | David Miller | MillerDavid@gmail.com   |
|        3 | John Doe     | 998John_Doe@gmail.com   |
|        4 | John Smith   | 999John_Smith@gmail.com |
+----------+--------------+-------------------------+
3 rows in set (0.00 sec)

Updated on: 08-Nov-2019

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements