The INSERT INTO SELECT
statement in SQL is used to insert data into a table from the result of a SELECT
query. This is useful when you want to copy data from one table into another, or when you want to populate a table with data from a query result.
Here's the basic syntax of the INSERT INTO SELECT
statement:
INSERT INTO target_table (column1, column2, ...)
SELECT column1, column2, ...
FROM source_table
WHERE condition;
target_table
: The name of the table into which you want to insert the data.(column1, column2, ...)
: The columns in the target table into which you want to insert the data.source_table
: The name of the table from which you want to select the data.SELECT column1, column2, ...
: The columns you want to select from the source table.WHERE condition
: An optional condition to filter the rows selected from the source table.Example:
Let's say we have a table named customers
with columns customer_id
, first_name
, last_name
, and email
, and we want to create a new table important_customers
and insert data into it from customers
where the email domain is 'example.com':
CREATE TABLE important_customers ( customer_id INT, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(100) ); INSERT INTO important_customers (customer_id, first_name, last_name, email) SELECT customer_id, first_name, last_name, email FROM customers WHERE email LIKE '%@example.com';
This will insert rows into the important_customers
table, copying the data from the customers
table but only for customers whose email addresses end with '@example.com'.
It's important to ensure that the column types and order in the SELECT
query match the column types and order in the INSERT INTO
clause to avoid any errors. Additionally, make sure that the target table is properly structured to accommodate the data being inserted