Copy all rows of a table to another table in MySQL?

MySQLMySQLi Database

To copy all rows of a table to another table, use the below syntax −

insert into yourTableName2(yourColumnName1,...N) select yourColumnName1,..N from yourTableName1;

Let us first create a table −

mysql> create table DemoTable1(FirstName varchar(100));
Query OK, 0 rows affected (1.11 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values('John');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values('Bob');
Query OK, 1 row affected (0.40 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| John      |
| Chris     |
| Bob       |
+-----------+
3 rows in set (0.00 sec)

Following is the query to create second table −

mysql> create table DemoTable2 (EmployeeName varchar(100));
Query OK, 0 rows affected (0.78 sec)

Following is the query to copy all rows of a table to another table −

mysql> insert into DemoTable2(EmployeeName) select FirstName from DemoTable1;
Query OK, 3 rows affected (0.52 sec)
Records: 3 Duplicates: 0 Warnings: 0

Let us now check the records of the 2nd table, wherein we have set the records of 1st table −

mysql> select *from DemoTable2;

This will produce the following output −

+--------------+
| EmployeeName |
+--------------+
| John         |
| Chris        |
| Bob          |
+--------------+
3 rows in set (0.00 sec)
raja
Published on 22-Aug-2019 14:35:17
Advertisements