How to optimize many SELECTs in a single table in MySQL?


To optimize many SELECTs, use it once and apply IN() to fetch multiple values. Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   Name varchar(100),
   Age int
);
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1,'Chris',23);
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable values(2,'David',21);
Query OK, 1 row affected (0.56 sec)
mysql> insert into DemoTable values(3,'Mike',24);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values(4,'Robert',22);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable ;

This will produce the following output −

+------+--------+------+
| Id   | Name   | Age  |
+------+--------+------+
|    1 | Chris  |   23 |
|    2 | David  |   21 |
|    3 | Mike   |   24 |
|    4 | Robert |   22 |
+------+--------+------+
4 rows in set (0.00 sec)

Following is the query to optimize many SELECTs on a single table −

mysql> select Name from DemoTable where Age in(21,22,23);

This will produce the following output −

+--------+
| Name   |
+--------+
| Chris  |
| David  |
| Robert |
+--------+
3 rows in set (0.00 sec)

Updated on: 01-Oct-2019

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements