How can we create a table from an existing MySQL table in the database?


With the help of CTAS i.e. “Create Table AS Select” script we can create a table from an existing table. It copies the table structure as well as data from the existing table. Consider the following example in which we have created a table named EMP_BACKUP from already existing table named ‘Employee’ −

mysql> Select * from Employee;
+------+--------+
| Id   | Name   |
+------+--------+
| 100  | Ram    |
| 200  | Gaurav |
| 300  | Mohan  |
+------+--------+
3 rows in set (0.00 sec)

The query above shows the data in table ’Employee’ and the query below will create the table named ‘EMP_BACKUP’ by copying the structure as well as data from the ‘Employee’ table.

mysql> Create table EMP_BACKUP AS SELECT * from EMPLOYEE;
Query OK, 3 rows affected (0.15 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> Select * from EMP_BACKUP;
+------+--------+
| Id   | Name   |
+------+--------+
| 100  | Ram    |
| 200  | Gaurav |
| 300  | Mohan  |
+------+--------+
3 rows in set (0.00 sec)

We can observe that it copied all the data and structure of the ‘Employee’ table.

Swarali Sree
Swarali Sree

I love thought experiments.

Updated on: 28-Jan-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements