WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

SQL INSERT INTO SELECT Statement


With SQL, you can copy information from one table to another.

INSERT INTO SELECT statement copies data from a table and inserts the data into an existing table.


SQL INSERT INTO SELECT statement

INSERT INTO SELECT statement copies data from a table and inserts the data into an existing table. Any existing rows in the target table will not be affected.

SQL INSERT INTO SELECT syntax

We can copy all columns from one table and insert them into another existing table:

INSERT INTO table2
SELECT * FROM table1;

Or we can just copy the desired column and insert it into another existing table:

INSERT INTO table2
(column_name (s))
SELECT column_name (s)
FROM table1;


Demo database

In this tutorial, we will use the welookups sample database.

Here is the data from the "Websites" table:

+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Google       | https://www.google.cm/  | 1     | USA     |
| 2  |  Indiatimes          | https://www.Indiatimes.com/ | 13    | IN      |
| 3  | zomato      | http://www.zomato.com/  | 4689  | IN      |
| 4  | indiamart          | http://indiamart.com/       | 20    | IN      |
| 5  | Facebook     | https://www.facebook.com/| 3     | USA     |
| 7  | stackoverflow | http://stackoverflow.com/|   0 | IND     |
+----+---------------+---------------------------+-------+---------+

Here is the data for the "apps" APP:

mysql> SELECT * FROM apps;
+----+------------+-------------------------+---------+
| id | app_name   | url                     | country |
+----+------------+-------------------------+---------+
|  1 | zomato    | http://zomato.com/     | IN      |
|  2 | stackoverflow APP | http://stackoverflow.com/     | IN      |
|  3 | Facebook APP | https://www.facebook.com/| IN      |
+----+------------+-------------------------+---------+
3 rows in set (0.00 sec)


SQL INSERT INTO SELECT instance

Copy the data from "apps" and insert it into "Websites":

Example

INSERT INTO Websites (name, country)
SELECT app_name, country FROM apps;

Only copy stackoverflow APP to "Websites":

Example

INSERT INTO Websites (name, country)
SELECT app_name, country FROM apps
WHERE id=1;