SQL SQL Tutorial SQL Database



SQL Insert Into Select

Structured Query Language (SQL) is a programming language used to manage and manipulate relational databases. One of the most commonly used SQL statements is the INSERT INTO SELECT statement. This statement allows you to insert data into a table from another table or a query result set.

The INSERT INTO SELECT statement is useful when you want to copy data from one table to another or when you want to combine data from multiple tables into a single table. It is also useful when you want to filter and transform data before inserting it into a table.

The basic syntax of the INSERT INTO SELECT statement is as follows:

INSERT INTO table_name (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table_name
WHERE condition;

The INSERT INTO SELECT statement consists of two parts: the INSERT INTO clause and the SELECT clause. The INSERT INTO clause specifies the name of the table and the columns into which you want to insert data. The SELECT clause specifies the columns from which you want to select data.

Here is an example of how to use the INSERT INTO SELECT statement:

INSERT INTO customers (first_name, last_name, email)
SELECT first_name, last_name, email
FROM users
WHERE role = 'customer';

This statement inserts data into the customers table from the users table. It selects the first_name, last_name, and email columns from the users table where the role is 'customer' and inserts them into the corresponding columns in the customers table.

You can also use the INSERT INTO SELECT statement to insert data into a table from a query result set. Here is an example:

INSERT INTO sales (product_id, quantity, price)
SELECT product_id, SUM(quantity), AVG(price)
FROM orders
GROUP BY product_id;

This statement inserts data into the sales table from a query result set. It selects the product_id column from the orders table and calculates the sum of the quantity and the average of the price for each product_id. It then inserts the product_id, quantity, and price values into the corresponding columns in the sales table.

The INSERT INTO SELECT statement is a powerful tool for managing and manipulating data in relational databases. It allows you to insert data into a table from another table or a query result set, and it can be used to filter and transform data before inserting it into a table.

Conclusion

The INSERT INTO SELECT statement is an essential SQL statement that allows you to insert data into a table from another table or a query result set. It is a powerful tool for managing and manipulating data in relational databases, and it can be used to filter and transform data before inserting it into a table.

References

Activity