sql insert into select

Galaxy Glossary

How can I insert data from one table into another table using a SELECT statement?

The `INSERT INTO SELECT` statement allows you to copy data from one table to another. It's a powerful tool for populating tables with data from existing tables or queries. This is often used for data migration or creating backups.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The `INSERT INTO SELECT` statement is a crucial part of SQL for data manipulation. It allows you to insert data from one table into another table. This is often used when you need to copy data from one table to another, or when you need to insert data based on a specific condition or calculation. It's a more efficient way to copy data than using multiple `INSERT` statements. The statement combines the `INSERT` command with a `SELECT` statement, allowing you to specify the source table and the columns to be copied. This is a very common technique in database design and management. For example, you might use it to migrate data from an old database table to a new one, or to populate a new table with data based on a specific criteria from an existing table.

Why sql insert into select is important

The `INSERT INTO SELECT` statement is important because it provides a concise and efficient way to copy data between tables. It's a fundamental skill for database administrators and developers, enabling data migration, backups, and complex data manipulation tasks.

Example Usage

```sql -- Create two sample tables CREATE TABLE Customers ( CustomerID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50) ); CREATE TABLE NewCustomers ( CustomerID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50) ); -- Insert data into Customers table INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES (1, 'John', 'Doe'), (2, 'Jane', 'Smith'); -- Insert data from Customers into NewCustomers based on a condition INSERT INTO NewCustomers (CustomerID, FirstName, LastName) SELECT CustomerID, FirstName, LastName FROM Customers WHERE CustomerID > 1; -- Verify the data in NewCustomers SELECT * FROM NewCustomers; ```

Common Mistakes

Want to learn about other SQL terms?