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


Result: StudentsBackup now contains:

id name dept marks
1 John IT 85
2 Emma HR 90
3 Raj IT 76

 Example 2: Copy Students from IT Department Only


Result: Only IT students are copied:

id name dept marks
1 John IT 85
3 Raj IT 76

 Key Points

  1. Combines SELECT and INSERT in a single operation.

  2. Useful for copying data between tables or archiving records.

  3. Columns in INSERT and SELECT must match in number and data type.

  4. Optional WHERE clause allows you to filter data before inserting.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *