How to execute multiple select queries in MySQL ?

MySQLMySQLi Database

To execute multiple select queries in MySQL, use the concept of DELIMITER. Let us first create a table −

mysql> create table DemoTable1
(
   Title text
)ENGINE=MyISAM;
Query OK, 0 rows affected (0.30 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values('The database MySQL is less popular than MongoDB') ;
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1 values('Java language uses MySQL database');
Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable1 values('Node.js uses the MongoDB') ;
Query OK, 1 row affected (0.05 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-------------------------------------------------+
| Title                                           |
+-------------------------------------------------+
| The database MySQL is less popular than MongoDB |
| Java language uses MySQL database               |
| Node.js uses the MongoDB                        |
+-------------------------------------------------+
3 rows in set (0.00 sec)

Following is the query to create the second table −

mysql> create table DemoTable2
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY
);
Query OK, 0 rows affected (0.45 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(),(),(),(),(),(),(),(),();
Query OK, 9 rows affected (0.19 sec)
Records: 9 Duplicates: 0 Warnings: 0

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
+----+
9 rows in set (0.00 sec)

Following is the query to execute multiple select queries −

mysql> DELIMITER //
mysql> select *from DemoTable1;
select *from DemoTable2;
//

This will produce the following output displaying the result of both the select statements −

+-------------------------------------------------+
| Title                                           |
+-------------------------------------------------+
| The database MySQL is less popular than MongoDB |
| Java language uses MySQL database               |
| Node.js uses the MongoDB                        |
+-------------------------------------------------+
3 rows in set (0.00 sec)
+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
+----+
9 rows in set (0.03 sec)
raja
Published on 04-Oct-2019 07:31:49
Advertisements