Summary: in this tutorial, you will learn how to use the MySQL
INSERT INTO SELECT statement to insert data into a table, where data comes from the result of a SELECT statement.
MySQL INSERT INTO SELECT Overview
In the previous tutorial, you learned how to insert one or more rows into a table using the
INSERT statement with a list of column values specified in the VALUES clause.
Besides using row values in the
VALUES clause, you can use the result of a SELECT statement as the data source for the INSERT statement.
The following illustrates the syntax of the
INSERT INTO SELECT statement:
In this syntax, instead of using the
VALUES clause, you can use a SELECT statement. The SELECT statement can retrieve data from one or more tables.
The
INSERT INTO SELECT statement is very useful when you want to copy data from other tables to a table or to summary data from multiple tables into a table.
MySQL INSERT INTO SELECT example
First, create a new table called
suppliers :
Note that you will learn how to create a new table in the subsequent tutorial. For now, you just need to execute this statement to create the
suppliers table.
Suppose all customers from
California, USA become the company’s suppliers. The following query finds all customers who locate in California, USA:
Second, use the
INSERT INTO ... SELECT statement to insert customers who locate in California USA from the customers table into the suppliers table:
It returned the following message indicating that 11 rows have been inserted successfully.
Third, verify the insert by querying data from the
suppliers table:
Here is the output:

Using SELECT statement in the VALUES list
First, create a new table called
stats:
Second, use the
INSERT statement to insert values that come from the SELECT statements:
In this example:
- First, use the
SELECTstatements with theCOUNT()functions to get the total products, employees, and orders. - Second, use the values returned from the
SELECTstatement in place of values in theVALUESclause of theINSERTstatement.
Third, query data from the table
stats:
In this tutorial, you have learned how to use the MySQL
INSERT INTO SELECT statement to insert data into a table from a result set.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.