Computer >> Computer tutorials >  >> Programming >> MySQL

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','[email protected]');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('David Miller','[email protected]');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('John Doe','[email protected]');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('John Smith','[email protected]');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('Adam Smith','[email protected]');
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  | [email protected]      |
|        2 | David Miller | [email protected]   |
|        3 | John Doe     | [email protected]   |
|        4 | John Smith   | [email protected] |
|        5 | Adam Smith   | [email protected]    |
+----------+--------------+-------------------------+
5 rows in set (0.00 sec)

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

mysql> select * from DemoTable1618 where ClientEmailId IN('[email protected]','[email protected]','[email protected]');

This will produce the following output −

+----------+--------------+-------------------------+
| ClientId | ClientName   | ClientEmailId           |
+----------+--------------+-------------------------+
|        2 | David Miller | [email protected]   |
|        3 | John Doe     | [email protected]   |
|        4 | John Smith   | [email protected] |
+----------+--------------+-------------------------+
3 rows in set (0.00 sec)