- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert data from one table to another in MySQL?
To insert data from one table to another, use the INSERT INTO SELECT statement. Let us first create a table −
mysql> create table DemoTable1 -> ( -> Id int, -> FirstName varchar(20) -> ); Query OK, 0 rows affected (0.49 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(101,'Adam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1 values(102,'John'); Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+------+-----------+ | Id | FirstName | +------+-----------+ | 101 | Adam | | 102 | John | +------+-----------+ 2 rows in set (0.00 sec)
Following is the query to create the second table −
mysql> create table DemoTable2 -> ( -> EmployeeId int, -> EmployeeName varchar(20) -> ); Query OK, 0 rows affected (0.42 sec)
Here is the query to insert data from one table to another in MySQL −
mysql> insert into DemoTable2(EmployeeId,EmployeeName) select Id,FirstName from DemoTable1; Query OK, 2 rows affected (0.15 sec) Records: 2 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 | +------------+--------------+ | 101 | Adam | | 102 | John | +------------+--------------+ 2 rows in set (0.00 sec)
Advertisements