MySQL INSERT SELECT Explained: Syntax & Examples

In MySQL, the SELECT INSERT statement is used to insert the results of a SELECT query into another table. The syntax is as follows:

INSERT INTO table_name (column1, column2, ...)
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Here, table_name is the name of the table where data will be inserted, column1, column2, … are the columns to be inserted, SELECT column1, column2, … FROM table_name is the data to be queried, WHERE condition is an optional criteria.

Here is an example of inserting data from one table into another table:

INSERT INTO users_copy (id, name, age)
SELECT id, name, age
FROM users
WHERE age > 18;

In the example above, we select data from the users table that meets the condition age > 18 and insert it into the corresponding columns in the users_copy table.

bannerAds