How to copy rows from one table to another in MySQL?

MySQLMySQLi Database

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

mysql> create table DemoTable1879
   (
   Id int,
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1879 values(101,'Chris Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1879 values(102,'David Miller');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1879 values(103,'Adam Smith');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1879;

This will produce the following output −

+------+--------------+
| Id   | Name         |
+------+--------------+
|  101 | Chris Brown  |
|  102 | David Miller |
|  103 | Adam Smith   |
+------+--------------+
3 rows in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable1880
   (
   ClientId int,
   ClientName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Here is the query to copy rows from one table to another −

mysql> insert into DemoTable1880(ClientId,ClientName) select Id,Name from DemoTable1879 where Id IN(101,103);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable1880;

This will produce the following output −

+----------+-------------+
| ClientId | ClientName  |
+----------+-------------+
|      101 | Chris Brown |
|      103 | Adam Smith  |
+----------+-------------+
2 rows in set (0.00 sec)
raja
Published on 27-Dec-2019 06:29:45
Advertisements