Insert the results of a MySQL select? Is it possible?


You do not need to use values whenever you insert the results of a select. To insert the results of select, let us first create two tables.

The first table query is as follows −

< FirstTableDemo>
mysql> create table FirstTableDemo
   −> (
   −> StudentId int,
   −> StudentName varchar(100)
   −> );
Query OK, 0 rows affected (0.41 sec)

Now create second table and after that insert the second table records in the first table using INSERT SELECT command.

The query to create the second table −

<SecondTableDemo>

mysql> create table SecondTableDemo
   −> (
   −> Id int,
   −> Name varchar(100)
   −> );
Query OK, 0 rows affected (0.47 sec)

Insert records in the table using insert command. The query is as follows −

mysql> insert into SecondTableDemo values(1,'John');
Query OK, 1 row affected (0.14 sec)

mysql> insert into SecondTableDemo values(2,'Sam');
Query OK, 1 row affected (0.27 sec)

Now we have two records in the second table. The query to display all records from table using select statement is as follows −

mysql> select *from SecondTableDemo;

The following is the output −

+------+------+
| Id   | Name |
+------+------+
|    1 | John |
|    2 | Sam  |
+------+------+
2 rows in set (0.00 sec)

Insert all records of second table into first table using INSERT SELECT statement −

mysql> insert into FirstTableDemo(StudentId,StudentName)
   −> select Id,Name from SecondTableDemo as tbl1
   −> where tbl1.Id not in (select StudentId from FirstTableDemo);
Query OK, 2 rows affected (0.57 sec)
Records: 2 Duplicates: 0 Warnings: 0

Now we have inserted all records of second table to the first table. Let us cross check using select statement. The query is as follows −

mysql> select *from FirstTableDemo;

The following is the output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | John        |
|         2 | Sam         |
+-----------+-------------+
2 rows in set (0.00 sec)

Updated on: 30-Jul-2019

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements