MySQL provides two ways to create a table based on another table:
- CREATE TABLE ... SELECT creates a table and populates it from the result set returned by an arbitrary SELECT statement. In this case, the "other table" is the set of rows and columns retrieved by the SELECT.
- CREATE TABLE ... LIKE creates an empty table using the definition of another existing table.
CREATE TABLE ... SELECT can create a table that is empty or non-empty, depending on what is returned by the SELECT part. The following statements create a table that contains the entire content of the Product table, a table that contains partial content from Product, and an empty copy of Product:
CREATE TABLE Product_Copy1 SELECT * FROM Product;
CREATE TABLE Product_Copy2 SELECT * FROM Product WHERE price > 50;
CREATE TABLE Product_Copy3 SELECT * FROM Product WHERE 0;
Using the LIKE keyword with CREATE TABLE creates an empty table based on the definition of another table. The result is a new table with a definition that includes all column attributes and indexes of the original table. Suppose that table tbl1 looks like this:
CREATE TABLE tbl1 (i INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(i)) ENGINE=InnoDB;
The result of CREATE TABLE ... LIKE differs from the result of using CREATE TABLE ... SELECT to create an empty table. Either of the following statements will create an empty copy of the table tbl1. However, the resulting copies differ in the amount of information retained from the original table structure:
CREATE TABLE tbl1_copy1 SELECT * FROM tbl1 WHERE 0;
CREATE TABLE tbl1_copy2 LIKE tbl1;
If you check structure of above tbl1_copy1 and tbl1_copy2 tables, you will find that the CREATE TABLE ... SELECT statement copies the column name and data type from the original table, but does not retain the PRIMARY KEY index information or the AUTO_INCREMENT column attribute information. The new table also uses the default storage engine, rather than the storage engine utilized by table tbl1. The copy created with CREATE TABLE ... LIKE has none of these problems.
Some table attributes are not copied, even when issuing CREATE TABLE ... LIKE. The most notable examples are:
- If the original table is a MyISAM table for which the DATA DIRECTORY or INDEX DIRECTORY table options are specified, those options are not copied to the new table. The data and index files for the new table will reside in the database directory for the chosen database.
- Foreign key definitions in the original table are not copied to the new table. If you wish to retain the foreign key definitions, they must be re-specified with ALTER TABLE after creating the copy.