MySQL INSERT INTO SELECT Statement
The INSERT INTO SELECT
statement in MySQL is used to copy data from one table and insert it into another table. This is particularly useful for transferring or archiving data between tables or databases.
Syntax
Key Components:
target_table
: The table where data will be inserted.source_table
: The table from which data will be selected.column1, column2, ...
: The columns in the target and source tables must match in number and data types.WHERE condition
: (Optional) Specifies which rows to copy from the source table.
Examples
1. Copy All Data Between Tables
Copy all rows and columns from one table to another.
Explanation:
- Copies of all rows and columns from
employees
toemployees_backup
.
2. Copy Specific Columns
Insert data into specific columns in the target table.
Explanation:
- Copies only the
employee_id
,name
, anddepartment
columns fromemployees
toemployees_backup
.
3. Copy Data with a Condition
Insert only selected rows based on a condition.
Explanation:
- Insert rows of employees earning more than 50,000 into
high_salary_employees
.
4. Copy Data Between Tables in Different Databases
Insert data into a table in another database.
Explanation:
- Copies rows of employees in the "Sales" department from the
current_db
database to thearchive_db
database.
5. Insert Data with Calculations
Insert data with derived values or transformations.
Explanation:
- Calculates the total sales and bonus (10% of sales) for each employee and inserts the results into
sales_summary
.
Common Use Cases
- Archiving Data:
- Move historical data to a backup or archive table.
- Data Transformation:
- Perform calculations or transformations while copying data.
- Merging Tables:
- Combine data from multiple source tables into one table.
- Creating Subsets:
- Create a table with filtered or summarized data for analysis.
Important Points
Column Matching:
- Ensure the columns in the
INSERT INTO
clause matches the columns in theSELECT
clause in terms of order and data type.
- Ensure the columns in the
Target Table Existence:
- The target table must exist before running the query. Use
CREATE TABLE
if needed.
- The target table must exist before running the query. Use
Avoid Duplicates:
- Use the
DISTINCT
keyword in theSELECT
query to prevent inserting duplicate rows:
- Use the
Error Handling:
- If the target table has unique constraints or foreign key constraints, ensure the inserted data complies with these rules.
Default and Auto-Increment Values:
- If the target table has columns with default values or
AUTO_INCREMENT
, you can exclude those columns in theINSERT INTO
clause.
- If the target table has columns with default values or
Performance Tips
Batch Inserts:
- For large data transfers, break the query into smaller batches to reduce lock contention.
Index Considerations:
- Disable or drop indexes on the target table during the insertion to speed up the process, and rebuild them afterward.
Use Temporary Tables:
- If transformations are complex, store intermediate results in a temporary table before final insertion.
Example: Copy Data Between Two Related Tables
Imagine two tables, orders
and order_archive
. To move completed orders to an archive table:
Let me know if you need further assistance or specific examples tailored to your use case!