Copy a table in SQL





In a relational database, sometimes there is a need to copy a table in SQL. This post talks about several different scenarios on doing this, and how to use SQL to accomplish each scenario.

Copy a table with all data

To copy a table with all the data, simply create a new table and populate the table with SELECT * from the original table. This will copy over the table structure as well as all the data that was in the original table.

The syntax you would use is

CREATE TABLE TABLE_NAME_2
SELECT * FROM TABLE_NAME 1;

Please note that this will not copy over the constraints or indexes associated with this table.


Copy just table structure (no data)

To copy the table structure without the data, the most generic way is to use the WHERE statement to ensure that no rows get copied over. An example would be something like the following:

CREATE TABLE TABLE_NAME_1
SELECT * FROM TABLE_NAME_2
WHERE 1=0;

Since 1=0 is always false, no data will be copied over.

The advantage of the above method is that it can be applied to all relational databases. There are additional methods you can use for each RDBMS to ensure that only the structure gets copied. For example, in MySQL, you can use the LIMIT keyword so that no data gets copied:

CREATE TABLE TABLE_NAME_2
SELECT * FROM TABLE_NAME_1 LIMIT 0

Copy some of the columns

Sometimes you may only want to copy over some of the columns instead of all of the columns. In this case, instead of using SELECT *, you would select just the columns you want to copy over.

Tags: Tags: ,