Computer >> Computer tutorials >  >> Programming >> MySQL

Insert data from one schema to another in MySQL?


To insert data from one scheme to another, the syntax is as follows. Here, we have two databases “yourDatabaseName1” and “yourDatabaseName2” −

insert into yourDatabaseName2.yourTableName2 select *from yourDatabaseName1.yourTableName1;

To understand the above syntax, let us create a table. We are creating a table in database “web” −

mysql> create table DemoTable2020
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2020 values(101,'Chris');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable2020 values(102,'David');
Query OK, 1 row affected (0.25 sec)

mysql> insert into DemoTable2020 values(103,'Mike');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2020;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
| 101  | Chris |
| 102  | David |
| 103  | Mike  |
+------+-------+
3 rows in set (0.00 sec)

Here is the query to create second table in another database “test” −

mysql> use test;
Database changed
mysql> create table DemoTable2021
   -> (
   -> StudentId int,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.60 sec)

Here is the query to MySQL inserting data from one schema to another −

mysql> insert into test.DemoTable2021 select *from web.DemoTable2020;
Query OK, 3 rows affected (0.18 sec)
Records: 3 Duplicates: 0 Warnings: 0

Display all records from the table using select statement −

mysql> select *from DemoTable2021;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 101       | Chris       |
| 102       | David       |
| 103       | Mike        |
+-----------+-------------+
3 rows in set (0.00 sec)