tags:

views:

1263

answers:

7

What is the SQL command to copy a table from one database to another database? I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database. Sorry if the question is too novice.

Thanks.

A: 

If you just want to copy the contents, you might be looking for select into: http://www.w3schools.com/Sql/sql_select_into.asp. This will not create an identical copy though, it will just copy every row from one table to another.

bzlm
+5  A: 

If the target table doesn't exist....

CREATE TABLE dest_table AS (SELECT * FROM source_table);

If the target table does exist

INSERT INTO dest_table (SELECT * FROM source_table);

Caveat: Only tested in Oracle

cagcowboy
Oracle? Hah! It can't even tell the difference between an empty varchar and a null. DB2 and I spit on your toy database :-).
paxdiablo
Above works on MySQL also
ConroyP
How do we specify the database with the above command?
Omnipotent
I might be mistaken, but I think for MySQL this doesn't necessarily preserve the keys of the original table.
Runcible
+2  A: 

Since your scenario involves two different databases, the correct query should be...

INSERT INTO Y..dest_table (SELECT * FROM source_table);

Query assumes, you are running it using X database.

Vijesh VP
+5  A: 

If your two database are separated, the simplest thing to do would be to create a dump of your table and to load it into the second database. Refer to your database manual to see how a dump can be performed.

Otherwise you can use the following syntax (for MySQL)

INSERT INTO database_b.table (SELECT * FROM database_a.table)
gizmo
A: 

At the command line

mysqldump somedb sometable -u user -p | mysql otherdb -u user -p

then type both passwords.

This works even if they are on different hosts (just add the -h parameter as usual), which you can't do with insert select.

Be careful not to accidentally pipe into the wrong db or you will end up dropping the sometable table in that db! (The dump will start with 'drop table sometable').

indentation
A: 

insert blah from select suggested by others is good for copying the data under mysql.

If you want to copy the table structure you might want to use the show create table Tablename; statement.

Zoredache
+3  A: 

Please check this link.. link text

Warrior