The INSERT INTO ... SELECT
statement in SQL is used to insert data into a table from another table or query result. It allows you to copy data between tables or insert data based on a query result. Here’s the basic syntax and some examples to help you understand how it works.
Basic Syntax
Explanation
target_table
: The table into which you want to insert the data.(column1, column2, column3, ...)
: The columns in the target table where you want to insert the data.source_table
: The table from which you are selecting the data.value1, value2, value3, ...
: The values to be inserted into the target table, typically coming from theSELECT
statement.WHERE condition
: A condition to filter which rows are selected from the source table.
Example 1: Basic Insert from One Table to Another
Suppose you have two tables: employees
and new_employees
. You want to copy all employees from the employees
table to the new_employees
table.
Example 2: Insert with a Condition
Suppose you only want to insert employees who were hired after January 1, 2024.
Example 3: Insert with Calculated Values
You can also insert data with calculated or static values. For example, inserting new employees with a default department.
Example 4: Insert into a Table from a Join
You can insert data from a join between multiple tables. For instance, if you want to insert data into target_table
from a join of table1
and table2
.
Things to Consider
- Data Types: Ensure that the data types of the columns in the
SELECT
statement match those of the columns in theINSERT INTO
table. - Constraints: Be aware of any constraints (like primary keys or unique constraints) on the target table that might affect your insert operation.
- Transactions: If inserting a large amount of data, consider using transactions to ensure data integrity and performance.