How to copy a table from one MySQL database to another?

MySQLMySQLi Database

The following is the syntax to copy a table from one database to another.

INSERT INTO yourDestinationDatabaseName.yourTableName SELECT * from yourSourceDatabaseName.yourtableName;

Let us see an example.

The CREATE command is used to create a table in the database ‘business’. We are creating a new table here.

<business>

mysql> use business;
Database changed
mysql> create table OriginalTable
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.46 sec)

Creating a new table in the database ‘test’.

<test>

mysql> use test;
Database changed
mysql> create table OriginalTable
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.47 sec

Records are inserted with the help of INSERT command in the first table.

mysql> use business;
Database changed
mysql> insert into OriginalTable values(1),(2),(3),(4);
Query OK, 4 rows affected (0.18 sec)
Records: 4  Duplicates: 0  Warnings: 0

To display all the records.

mysql> select *from OriginalTable;

Here is the output.

+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+
4 rows in set (0.00 sec)

To copy the above table from database “business” into another database “test”.

mysql>  INSERT INTO test.OriginalTable SELECT * from business.OriginalTable;
Query OK, 4 rows affected (0.20 sec)
Records: 4  Duplicates: 0  Warnings: 0

To check if the table has been copied.

mysql> use test;
Database changed
mysql> select *from OriginalTable;

The following output shows that the table “OriginalTable” have been copied successfully into the second database.

+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+
4 rows in set (0.00 sec)
raja
Published on 21-Nov-2018 07:30:42
Advertisements