In this tutorial, we will defer from that and look at the INSERT INTO — SELECT statement that we can use to insert values in a table where the values are from the result of a SELECT statement.
Basic Usage
If you can recall the basic INSERT INTO clause in MySQL, we can add data as:
However, we can use the SELECT statement instead of the VALUES clause.
The general syntax is:
The query above uses the SELECT clause to select specified values from other tables and insert them into the set table.
In most cases, we use the INSERT INTO — SELECT clause when copying values from another table or only sections of the values from a table.
Example Use Case
Let me illustrate how we can use the INSERT INTO with the SELECT statement using a real-world database.
NOTE: For this example, I will be using the Sakila database for illustrations. Feel free to use any other database or download a copy of the Sakila sample database from the resource provided below:
https://dev.mysql.com/doc/index-other.html
Let us start by creating a table that will contain the data as shown in the queries below:
DROP TABLE IF EXISTS currated_info;
CREATE TABLE currated_info(
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100),
rating VARCHAR(50),
film_length INT
);
Finally, we can use INSERT INTO statement for the table above as shown in the query below:
INSERT INTO currated_info (title, rating, film_length) SELECT title, rating, length FROM film;
Once the query has executed successfully, we can query the curated_table and see the data as shown below:
Database changed
mysql> select * FROM currated_info LIMIT 5;
+----+------------------+--------+-------------+
| id | title           | rating | film_length |
+----+------------------+--------+-------------+
|Â 1 | ACADEMY DINOSAUR | PGÂ Â Â Â |Â Â Â Â Â Â Â Â Â 86 |
|Â 2 | ACE GOLDFINGERÂ Â | GÂ Â Â Â Â |Â Â Â Â Â Â Â Â Â 48 |
|Â 3 | ADAPTATION HOLES | NC-17Â |Â Â Â Â Â Â Â Â Â 50 |
|Â 4 | AFFAIR PREJUDICE | GÂ Â Â Â Â |Â Â Â Â Â Â Â Â 117 |
|Â 5 | AFRICAN EGGÂ Â Â Â Â | GÂ Â Â Â Â |Â Â Â Â Â Â Â Â 130 |
+----+------------------+--------+-------------+
5 rows in set (0.00 sec)
As you can see, we can use the select statement instead of the values clause to add values to a table.
NOTE: Be careful when using the select statement on a large database as it might slow down the database or cause a crash.
Conclusion
In this tutorial, we quickly learned how to use the MySQL INSERT INTO clause with the SELECT statement to add data from the result of a select query.