SQL Insert Into Select
The SQL statement “INSERT INTO SELECT” is used to insert data into a table from the result of a SELECT statement. It allows you to copy data from one or more tables and insert it into another table.
Here’s the general syntax of the “INSERT INTO SELECT” statement:
INSERT INTO destination_table (column1, column2, ...) SELECT column1, column2, ... FROM source_table WHERE conditions;
Let’s break down the syntax:
INSERT INTO destination_tablespecifies the name of the table where you want to insert the data.
(column1, column2, ...)specifies the columns of the destination table where you want to insert data. This is optional; if you omit it, all columns will be assumed.
SELECT column1, column2, ...specifies the columns from the source table that you want to insert into the destination table.
FROM source_tablespecifies the name of the table or tables from which you want to select data.
WHERE conditionsis optional and specifies any conditions that must be met for the data to be inserted. You can use this to filter the rows you want to insert.
Here’s an example to illustrate the usage:
INSERT INTO employees_copy (employee_id, first_name, last_name) SELECT employee_id, first_name, last_name FROM employees WHERE department = 'Sales';
In this example, we’re inserting data into the
employees_copy table, selecting the
last_name columns from the
employees table. We’re only inserting the rows where the
department is ‘Sales’.
Make sure the column names and data types of the source and destination tables match appropriately for a successful insertion.