MySQL INSERT INTO SELECT Statement

The INSERT INTO SELECT statement in MySQL is used to copy data from one table and insert it into another table. This can be very useful if you want to make a backup of a table, create a summary table, or insert data from one table into another based on specific criteria.

Syntax 

The basic syntax for the INSERT INTO SELECT statement in MySQL is as follows:

INSERT INTO target_table (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM source_table
WHERE conditions;

If the target table and the source table have the same structure (same columns with data types), the syntax can be simplified:

INSERT INTO target_table
SELECT * FROM source_table
WHERE conditions;

Demo Database:

For our demonstration, we'll use the following tables:

students:

student_idstudent_nameage
1Alice20
2Bob22
graduates (empty):

grad_idgrad_nameage

Examples

Insert all students into the graduates table:

INSERT INTO graduates (grad_id, grad_name, age)
SELECT student_id, student_name, age
FROM students;

After this query, the graduates table will have the same records as the students table. 

Insert students older than 21 into the graduates table:

INSERT INTO graduates (grad_id, grad_name, age)
SELECT student_id, student_name, age
FROM students
WHERE age > 21;

After this query, only "Bob" will be added to the graduates table. 

Summary

The INSERT INTO SELECT statement provides a powerful way to transfer data from one table to another in MySQL. This is especially useful for backing up data, creating summary tables, or populating tables based on specific criteria. 

Care should be taken to ensure that the target table's structure matches the data being inserted, as this is a common source of errors. The flexibility and efficiency of this command make it an invaluable tool for database administrators and developers.


Comments