Insert into ... values ( SELECT ... FROM ... )
What if you want to insert multiple rows into a table by selecting them from another? This technique allows you to copy data efficiently from one table to another using INSERT INTO ... VALUES (SELECT ... FROM ...).
If you want to insert data into a table by selecting it from another, SQL makes this pretty straightforward using the INSERT INTO ... SELECT ... FROM ... syntax. This method is super useful when you need to migrate or duplicate data across tables without manually inputting every row.
Here’s how it works:
INSERT INTO target_table (column1, column2)
SELECT column1, column2 FROM source_table
WHERE condition;
Why use this method?
- Bulk data transfer: Move multiple rows at once from one table to another.
- Avoid manual entry: Save time by skipping individual INSERT statements.
- Flexible filtering: Use WHERE, JOIN, or GROUP BY to customize what gets inserted.
Example:
Imagine you have a table called employees_temp and you want to move the employees who joined in 2024 to the main employees table:
INSERT INTO employees (id, name, department)
SELECT id, name, department FROM employees_temp
WHERE join_year = 2024;
A few tips:
- Make sure the columns in the SELECT match the columns you're inserting into in terms of order and data types.
- You don’t need to use VALUES here. Just directly follow INSERT INTO with the SELECT block.
- Always test with a small dataset or within a transaction if you're unsure.