MySQL Copy Table With Examples
1. Copy Table Structure Only
To duplicate a table without copying data, use:
✅ This copies the table structure, including columns, indexes, and constraints (except FOREIGN KEY
constraints).
Example
✅ This creates an empty employees_backup
table with the same structure as employees
.
2. Copy Table Structure and Data
To copy both structure and data, use INSERT INTO ... SELECT *
:
Example
✅ This duplicates the a employees
table along with all records.
3. Copy Table with Selected Columns Only
If you want to copy specific columns, specify them in the SELECT
statement:
Example
✅ This copies only id
, name
, and department
columns.
4. Copy Table with a Condition
To copy only certain records, add a WHERE
clause:
Example
✅ This copies only active employees.
5. Copy Table Without AUTO_INCREMENT Values
To reset the AUTO_INCREMENT column in the copied table:
✅ This ensures new IDs start from 1.
6. Copy Table and Rename Columns
To rename columns in the copied table:
Example
✅ This copies data while renaming columns.
7. Copy Table with Indexes and Constraints
To copy indexes and constraints along with data, use:
✅ Disabling keys speeds up insertion for large datasets.
8. Copy Table to Another Database
To copy a table from one database to another:
Example
✅ Copies employees
from company_db
to backup_db
.
9. Conclusion
Copy Type | Method |
---|---|
Only structure | CREATE TABLE new_table LIKE original_table; |
Structure + Data | CREATE TABLE new_table LIKE original_table; INSERT INTO new_table SELECT * FROM original_table; |
Specific Columns | CREATE TABLE new_table AS SELECT column1, column2 FROM original_table; |
With Conditions | CREATE TABLE new_table AS SELECT * FROM original_table WHERE condition; |
With Reset AUTO_INCREMENT | ALTER TABLE new_table AUTO_INCREMENT = 1; |
Copy to Another Database | CREATE TABLE new_db.new_table LIKE old_db.original_table; INSERT INTO new_db.new_table SELECT * FROM old_db.original_table; |
🚀 Choose the right method to efficiently copy MySQL tables!