home | contact us
» mysql » MySQL Copy Table from One Database to Another

BLOG CATEGORY: mysql programming web development


Sometime in MySQL you want to copy an entire table from one database to a separate database. One example of when you would want to do this is if you are making a backup of a table before you apply some kind of processing to that table. There is nothing worse than ruining a database table and losing valuable information. To make an instant backup is so easy that there really is no excuse not to make backups at important or risky stages.

Here is how to do it:

[mysql]
DROP TABLE IF EXISTS backup_db.backup_table;
CREATE TABLE backup_db.backup_table SELECT * FROM live_db.live_table;
[/mysql]

This will delete your existing backup table completely, then will remake it copying all structural information and content from the live_table in the live_db.

Related Blogs
http://www.phpclasses.org/browse/package/4017.html
http://www.sematopia.com/?p=61
http://www.yinfor.com/blog/archives/2008/02/mysql_backup_and_recovery_meth.html


Click Here to Contact Us about MySQL Copy Table from One Database to Another
 

Comments

40 Comments

40 Responses to “MySQL Copy Table from One Database to Another”

  1. Julz says:

    Just remember that this won’t create the table using the same engine as the existing table and it won’t recreate the primary keys or indexes.

    To do this you have to use:

    CREATE TABLE new_table_name LIKE old_table_name;

    then you populate it with the data from the old table with:

    INSERT INTO new_table_name SELECT * FROM old_table_name;

    If the copied old table has many keys then it may help to speed the INSERT if you turn off the keys using the following before the INSERT:

    ALTER TABLE new_table_name DISABLE KEYS;

    And then after the INSERT:

    ALTER TABLE new_table_name ENABLE KEYS;

    These two statements are not supported by all MySQL Engine types though. InnoDB being one of them in MySQL ver 5.x

    Cheers
    Julz

  2. admin says:

    Nice one Julz

    Yes if you want to do more than simply backup the table data and want to actually make a proper fully functional copy of the table then the above is definitely the best way to do so.

  3. tony says:

    hi, i want to update my table2 with only the new data that i have entered from table1. hopefully on a daily basis

    how wud i go about this? pls help

    tony

  4. tony says:

    any one? please

  5. rigo says:

    Very useful tip, thanks to Julz and Admin

  6. admin says:

    Hi

    I made a little function for this query as per Julz advice

    function backup_table($table_name, $backup_table_name){
    	db_query("CREATE TABLE $backup_table_name LIKE $table_name");
    	db_query("ALTER TABLE $backup_table_name DISABLE KEYS");
    	db_query("INSERT INTO $backup_table_name SELECT * FROM $table_name");
    	db_query("ALTER TABLE $backup_table_name ENABLE KEYS");
    }
    
  7. admin says:

    note thats using this db_query function

    function db_query($query){
    	$output = mysql_query($query) or die('<h1 style="color: red;">MySQL Error:</h1>Please copy and paste between the lines and email to YOUREMAIL@ADDRESS.COM<br><br>------------------------------------------------------------------------------------<h3>Query:</h3>
    
    		
    
    <h3>MySQL Error:</h3>' . mysql_error() . '<br><br>------------------------------------------------------------------------------------');
    	return $output;
    }
    
  8. troy says:

    Hey Guys,

    Im running the mysql 5.1.2 & myphpadmin 3.1 and this doesnt seem to work.

    it tries to copy the table to the same database. Any help please?

  9. admin says:

    can you tell us the exact sql you are pasting into the sql box on phpmyadmin?

  10. ZIA says:

    Its so nice. Thaks for your conversations. But i need one more thing. how can i transfer a table data from one machine to another in MySQL?.

  11. admin says:

    the most usually way would be to dump the table data to an SQL file (export in phpMyAdmin)

    then save this file somewhere, upload it to the other machine and then import it.

    there are other ways involving getting the machines talkign to each other directly, but for most purposes the dump method is going to be the easiest and therefore best.

  12. tanvi says:

    hai,i tried your code..but it is not working

    I tried with this in phpmyadmin:

    1st db name :employees1 —>table name:hai
    2nd db name:employees —>table name:hai

    My code is:
    DROP TABLE IF EXISTS employees1.hai;
    CREATE TABLE employees1.hai SELECT * FROM employees.hai;

    but it shows error as in phpmyadmin.:

    MySQL said: Documentation
    #1103 – Incorrect table name ‘employees1.hai’ ..

    Please help me as early as possible…

  13. tanvi says:

    Please help me as soon as possible…
    Its very urgent..

  14. admin says:

    are they MyISAM tables?

  15. Steve Childs says:

    Make sure that the user you are running the query as has sufficient rights for both the source and destination databases…

    Also make sure you’re using the right quotes – you shouldn’t need to use quotes at all in those queries you posted, try it without.

    The queries as posted here do work, I’ve just done them on two of my tables. The problem lies in your SQL server somewhere, my guess is one of the above reasons.

  16. James Campanella says:

    To tanvi, I don’t know if you’ve solved your problem yet or not, but it appears to me that the problem is in your back tick quotes. If you are specifying a database.table the proper backticks should be database.table for it to work in phpMyAdmin. It is not a bad idea to use quotes in the event you have a database name or field that ends up being a MySQL keyword or SQL command. Hope this helps.

  17. admin says:

    Ah yeah well spotted James :)

  18. Where to find the best possible and secure database solutions for big databases ? any suggestions ?

  19. Andrei says:

    Hello,
    What about the copy to another server without mysqldump and gzip?

  20. syed says:

    How can i migrate a table from a database to another with different field names but field values are same. I also have extra columns to insert in new database table?

    Please help!!!

    Regards,
    syed

  21. naresh says:

    <?php

    $t_core_dir = dirname( __FILE__ ).DIRECTORY_SEPARATOR;

    require_once( $t_core_dir .'core.php' );
    helper_begin_long_process();

    $db1 = "ams";//first schema name to be copied
    $db2 = "newams";//second schema to be created with same data as db1
    $query = "use $db1";
    db_query($query );
    $query1 = "show tables from $db1";
    $result1 = db_query($query1 );
    $query2 = "create schema $db2";
    db_query($query2 );
    $row_count1 = db_num_rows( $result1);
    for ( $i=0 ; $i < $row_count1 ; $i++ ) {
    $t_col = "Tables_in_$db1";
    $row = db_fetch_array( $result1 );
    $t_copy_from = $db1.'.'.$row["$t_col"];
    $t_copy_to = $db2.'.'.$row["$t_col"];
    ECHO '’ . $t_copy_from . ‘ ‘ . $t_copy_to. ”;

    copy_db1_to_db2_table($t_copy_from,$t_copy_to);
    }

    function copy_db1_to_db2_table($table_name, $backup_table_name){

    db_query(“CREATE TABLE $backup_table_name LIKE $table_name”);

    db_query(“ALTER TABLE $backup_table_name DISABLE KEYS”);

    db_query(“INSERT INTO $backup_table_name SELECT * FROM $table_name”);

    db_query(“ALTER TABLE $backup_table_name ENABLE KEYS”);

    }

    ?>

  22. naresh says:

    this is for copying one DB schema to Another DB schema

  23. ijkui9jkj says:

    #
    db_query(“CREATE TABLE $backup_table_name LIKE $table_name”);
    #
    db_query(“ALTER TABLE $backup_table_name DISABLE KEYS”);
    #
    db_query(“INSERT INTO $backup_table_name SELECT * FROM $table_name”);
    #
    db_query(“ALTER TABLE $backup_table_name ENABLE KEYS”);
    #
    }

  24. aom says:

    thank you very much

    may I edit
    CREATE TABLE new.table SELECT * FROM old.table;

  25. Vincent says:

    how about if i want to copy the whole database in mysql? without using backup? just a query..help please…

  26. atul says:

    this query doesnt work for my sql
    CREATE TABLE backup_db.backup_table SELECT * FROM live_db.live_table;

    i tried with my database and table

  27. SM says:

    I would like to know how to update a table after it has been copied from another table. I mean that i need to update the new table with the other’s new inerted rows on a daily or monthly basis for example i.e. incrementally, does anyone know this can be done ??

  28. jairaj says:

    Hi,

    My database is on a server. It gets update every time and keep on filling the rows in my database. My friend’s database is on different server. I want to update my friend’s database as soon as my database gets any update. Please help me……

  29. Andre says:

    Hi,

    is there any way to copy the indexes as well??

    Cheers
    Andre

  30. newbie says:

    Hi,

    I have to copy only one column from one mysql db table to another running on different server. They have given me a wsdl for updating in destination db. the source database is in local environment. Can anyone please tell me how do I retrieve the data from sql convert into a SOAP webservice as defined by the wsdl? I have to do this in php. And I’m newbie.

    Any help would be greatly appreciated.

  31. ano says:

    the script will work if you are in the db other than the one you are altering-
    Example
    You want to copy A.a into B.a
    SCRIPT:
    >use B;
    >drop table if exists B.a;
    >use A;
    >create table B.a select * from a;

  32. JD says:

    these suggestions are overcomplicated. its pretty easy to copy the table create statement, run it in the new db and then run:

    INSERT INTO newDB.table
    SELECT *
    FROM oldDB.table;

    that copies all the indices and other table characteristics. plus, you don’t have to mess with drop table. i just did this for nine tables in less than 15 min.

    if you are asking, ‘how can i copy the CREATE statement’ you should get Sequel Pro or similarly awesome UI for your DB.

  33. Tendai Gomo says:

    This is all useful stuff. Thanks so much.

    What if i want to select a particular row at the front-end of an application using PHP code. Then, by clicking a button inside the row, the data is immediately transferred to another database?

  34. Green says:

    Hi, its a good explanation you made. Please, I want to seek your advice, I am working on a database and want to removed entirely part of the data (images), i.e. medical records that a are older to a new database which will serve as an archive and still link it to the original database. Please can u tell me how this can be done safely. Thanks!

  35. Sameer Naqvi says:

    Really helpful. I must say very good technique!!!

    Thank you so much…

  36. avishek says:

    Hi,

    When i copy one table from a db to another if the number is less its ok any possible code for multiple number of table particularly using a loop.

    Thanks

  37. Thanks for the post but there was one small typo if you are running this command on the sever itself. But worked fine after removing the (back ticks)

    CREATE TABLE backup_db.backup_table` SELECT * FROM live_db.live_table;

    worked other wise i got ERROR 1146 (42S02): Table ‘current_db.live_db.live_table’ doesn’t exist with back ticks.

Leave a Reply

rss icon