Explain Codes LogoExplain Codes Logo

In MySQL, how to copy the content of one table to another table within the same database?

sql
data-transfer
sql-queries
database-management
Alex KataevbyAlex Kataev·Dec 16, 2024
TLDR

To quickly replicate all data from existing_table to new_table, with matching structures, use INSERT INTO...SELECT:

-- Let's clone that data! INSERT INTO new_table SELECT * FROM existing_table;

If new_table has different columns, specify these and their matching sources:

-- Remapping columns, like playing musical chairs! INSERT INTO new_table(column1, column2) SELECT column1, column2 FROM existing_table;

Handling different data scenarios

Selective Data Transfer - Using WHERE clause

Need to copy only some rows? The WHERE clause is your friend!

-- And you thought shopping selectively only applied to groceries! INSERT INTO new_table SELECT * FROM existing_table WHERE condition;

Exact Structure Clone - CREATE TABLE LIKE

Want to an exact structure clone without data like a showroom piece? Here you go:

-- Because sometimes you just want an empty twin! CREATE TABLE new_table LIKE existing_table;

Both structure and data copying in one go

For cloning structure and data simultaneously, check this out:

-- All at once, because we're efficient like that! CREATE TABLE new_table SELECT * FROM existing_table;

Complex table structures? No problem!

Custom column mapping

For differently structured tables, align the column names:

-- Columns, assemble! Yes, you too, data types! INSERT INTO new_table(dest_col1, dest_col2) SELECT source_col1, source_col2 FROM existing_table;

Ensuring data integrity and efficiency

Stay smart! Preserve data integrity and efficiency by observing foreign keys, indexes, and constraints.

Advanced considerations for pros

On-the-fly data transformation

Modify data during the copy process using SQL functions:

-- Let's go Transformers on this data! INSERT INTO new_table SELECT CONCAT(first_name, ' ', last_name) as full_name FROM existing_table;

Handling bulky data transfers

For massive data, consider row chunking, batch inserts, or even temporary tables.

Taking care of auto-increment values

When dealing with auto-increment columns, take care to properly manage them, or they might bump into each other!