MySQL INSERT INTO SELECT Statement
MySQL INSERT INTO SELECT Statement
The INSERT INTO ... SELECT statement in MySQL is used to insert data from one table into another table.
This is useful when you want to copy data between tables without manually inserting each row.
Syntax
-
target_table→ Table where data will be inserted -
source_table→ Table from which data is selected -
WHERE→ Optional condition to filter rows
✅ The number of columns in INSERT must match the number of columns in SELECT.
🧠 Example Tables
Students2024
| id | name | dept | marks |
|---|---|---|---|
| 1 | John | IT | 85 |
| 2 | Emma | HR | 90 |
| 3 | Raj | IT | 76 |
StudentsBackup (Empty table with same columns)
| id | name | dept | marks |
|---|
Example 1: Copy All Students to Backup Table
| id | name | dept | marks |
|---|---|---|---|
| 1 | John | IT | 85 |
| 2 | Emma | HR | 90 |
| 3 | Raj | IT | 76 |
Example 2: Copy Students from IT Department Only
| id | name | dept | marks |
|---|---|---|---|
| 1 | John | IT | 85 |
| 3 | Raj | IT | 76 |
Key Points
-
Combines SELECT and INSERT in a single operation.
-
Useful for copying data between tables or archiving records.
-
Columns in
INSERTandSELECTmust match in number and data type. -
Optional
WHEREclause allows you to filter data before inserting.
