Select some data from a database table and insert into another table in the same database with MySQL

MySQLMySQLi Database

To insert data from a table to another, use INSERT INTO statement. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(101,'Chris',24);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1 values(102,'David',28);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1;

This will produce the following output −

+------+-----------+------+
| Id   | FirstName | Age  |
+------+-----------+------+
|  101 | Chris     |   24 |
|  102 | David     |   28 |
+------+-----------+------+
2 rows in set (0.00 sec)

Here is the query to create second table.

pre class="prettyprint notranslate" >
mysql> create table DemoTable2
     (
     EmployeeId int,
     EmployeeName varchar(20),
     EmployeeAge int
     );
Query OK, 0 rows affected (0.00 sec)

Following is the query to select some data from one database table and insert into another table in the same database −

mysql> insert into DemoTable2(EmployeeId,EmployeeName,EmployeeAge)
     select Id,FirstName,Age from DemoTable1 where Id=102;
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable2;

This will produce the following output −

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|        102 | David        |          28 |
+------------+--------------+-------------+
1 row in set (0.00 sec)
raja
Published on 23-Dec-2019 16:38:26
Advertisements