Insert values in a table by MySQL SELECT from another table in MySQL?


Fir this, use INSERT INTO SELECT statement. Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> Id int,
   -> Name varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (1.72 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(100,'Chris',24);
Query OK, 1 row affected (0.61 sec)
mysql> insert into DemoTable1 values(101,'Adam',23);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1 values(102,'John',25);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values(103,'Carol',26);
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1;

This will produce the following output −

+------+-------+------+
| Id   | Name | Age |
+------+-------+------+
|  100 | Chris |   24 |
|  101 | Adam  |   23 |
|  102 | John  |   25 |
|  103 | Carol |   26 |
+------+-------+------+
4 rows in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable2
   -> (
   -> EmployeeId int,
   -> EmployeeFirstName varchar(20),
   -> EmployeeAge int
   -> );
Query OK, 0 rows affected (1.63 sec)

Here is the query to insert values in DemoTable2 from MySQL select from DemoTable1 −

mysql> insert into DemoTable2(EmployeeId,EmployeeFirstName,EmployeeAge) select Id,Name,Age from DemoTable1 where Id=101;
Query OK, 1 row affected (0.17 sec)
Records: 1 Duplicates: 0 Warnings: 0

Let us check the table records −

mysql> select * from DemoTable2;

Here is the query to create second table −

+------------+-------------------+-------------+
| EmployeeId | EmployeeFirstName | EmployeeAge |
+------------+-------------------+-------------+
|        101 | Adam              |          23 |
+------------+-------------------+-------------+
1 row in set (0.00 sec)

Updated on: 05-Nov-2019

740 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements