bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/SQL/SQL Tutorial
SQL•SQL Tutorial

SQL INSERT INTO SELECT Statement

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind SQL INSERT INTO SELECT Statement?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The INSERT INTO SELECT statement is used to copy data from an existing table and insert it into another existing table.
INSERT INTO SELECT Syntax
The SQL INSERT INTO SELECT Statement

The SQL INSERT INTO SELECT Statement

The INSERT INTO SELECT statement is used to copy data from an existing table and insert it into another existing table.

The INSERT INTO SELECT statement requires that the data types in source and target tables match.

Note

The existing records in the target table are unaffected.

INSERT INTO SELECT Syntax

Copy all columns from one table to another table:

INSERT INTO
target_table
SELECT * FROM
source_table
WHERE
condition
;

Note

If you omit the column names, the number and order of columns in the source and target tables must be exactly the same!

Copy only some columns from one table to another table:

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

Demo Database

Below is a selection from the "Customers" table:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico

And a selection from the "Suppliers" table:

SupplierIDSupplierNameContactNameAddressCityPostal CodeCountry
1Exotic LiquidCharlotte Cooper49 Gilbert St.LondonaEC1 4SDUK
2New Orleans Cajun DelightsShelley BurkeP.O. Box 78934New Orleans70117USA
3Grandma Kelly's HomesteadRegina Murphy707 Oxford Rd.Ann Arbor48104USA

Example

Copy "Suppliers" into "Customers" (the columns that are not filled with data, will contain NULL):

INSERT INTO Customers (CustomerName,
 City, Country)
 SELECT SupplierName, City, Country FROM Suppliers;

Example

Copy "Suppliers" into "Customers" (copy all columns):

INSERT INTO Customers
SELECT * FROM Suppliers;

Example

Copy only the German suppliers into "Customers":

INSERT INTO Customers (CustomerName,
 City, Country)
 SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';

Previous

SQL SELECT INTO Statement

Next

SQL CASE Expression