Search code examples
mysqlcomposite-primary-keycreate-table

Primary keys in MySQL


I am trying to create a table from an existing table. Will the primary keys from the existing table transfer over to the new table?

create table B as select column1, column2, column3 from A.

In table A, the primary keys are column1 and column2.


Solution

  • CREATE TABLE ... SELECT does not automatically create any indexes for you. This is done intentionally to make the statement as flexible as possible. If you want to have indexes in the created table, you should specify these before the SELECT statement:

    mysql> CREATE TABLE bar (UNIQUE (n)) SELECT n FROM foo;
    

    Documentation