Use UNION ALL to insert records in two tables with a single query in MYSQL

MySQLMySQLi Database

Here is the query to create first table.

mysql> create table DemoTable1
   -> (
   -> StudentName varchar(20),
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.67 sec)

To understand the above concept, let us create second table.

mysql> create table DemoTable2
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values('Chris');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable2;

This will produce the following output −

+-------+
| Name  |
+-------+
| Chris |
+-------+
1 row in set (0.00 sec)

Here is the query to select and insert records with a single MySQL query −

mysql> insert into DemoTable1
   -> select Name,89 from DemoTable2
   -> union all
   -> select Name,98 from DemoTable2;
Query OK, 2 rows affected (0.15 sec)
Records: 2  Duplicates: 0  Warnings: 0

Now you can select records from the first table −

mysql> select * from DemoTable1;

This will produce the following output −

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           89 |
| Chris       |           98 |
+-------------+--------------+
2 rows in set (0.00 sec)
raja
Published on 10-Dec-2019 06:35:57
Advertisements