MySQL query to copy records from one table to another with different columns


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

mysql> create table DemoTable1900
   (
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(20),
   ClientAge int default 29
   ) auto_increment=1000;
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1900(ClientName,ClientAge) values('Chris',45);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1900(ClientName,ClientAge) values('David',29);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1900(ClientName,ClientAge) values('Mike',37);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1900(ClientName) values('Sam');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1900;

This will produce the following output −

+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
|     1000 | Chris      |        45 |
|     1001 | David      |        29 |
|     1002 | Mike       |        37 |
|     1003 | Sam        |        29 |
+----------+------------+-----------+
4 rows in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable1901
   (
   EmployeeId int,
   EmployeeName varchar(20),
   EmployeeAge int
   );
Query OK, 0 rows affected (0.00 sec)

Here is the query to copy records from one table to another with different columns −

mysql> insert into DemoTable1901(EmployeeId,EmployeeName,EmployeeAge)
   select ClientId,ClientName,
   ClientAge from DemoTable1900;
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable1901;

This will produce the following output −

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|       1000 | Chris        |          45 |
|       1001 | David        |          29 |
|       1002 | Mike         |          37 |
|       1003 | Sam          |          29 |
+------------+--------------+-------------+
4 rows in set (0.00 sec)

Updated on: 27-Dec-2019

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements