About Lesson
SQL SELECT INTO Statement
The SELECT INTO
statement is used to create a new table and insert data into it by selecting data from another table.
Syntax
SELECT column1, column2, column3, ...
INTO new_table
FROM existing_table
WHERE condition;
Example: Basic Usage
SELECT customer_id, customer_name, contact_name
INTO CustomersBackup
FROM Customers
WHERE country = 'Germany';
This query creates a new table called CustomersBackup
and inserts into it the customer_id
, customer_name
, and contact_name
of customers from Germany.
Example: Copy All Columns
SELECT *
INTO CustomersBackup
FROM Customers
WHERE country = 'Germany';
This query creates a new table called CustomersBackup
and inserts all columns of customers from Germany into it.
Sample Tables
Consider the following Customers
table:
Customers:
| customer_id | customer_name | contact_name | country |
|-------------|---------------|--------------|---------|
| 1 | Alfreds Futterkiste | Maria Anders | Germany |
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Mexico |
| 3 | Antonio Moreno Taquería | Antonio Moreno | Mexico |
| 4 | Around the Horn | Thomas Hardy | UK |
| 5 | Berglunds snabbköp | Christina Berglund | Sweden |
Result of SELECT INTO
After running the first example query, the new table CustomersBackup
would look like this:
CustomersBackup:
| customer_id | customer_name | contact_name |
|-------------|---------------|--------------|
| 1 | Alfreds Futterkiste | Maria Anders |
| 6 | Blauer See Delikatessen | Hanna Moos |
| 11 | Frankenversand | Peter Franken |
| 13 | G'moritz | Martin Sommer |
Important Notes
- The
SELECT INTO
statement creates a new table in the database by copying selected columns and data from an existing table. - If you only want to insert data into an existing table, use the
INSERT INTO SELECT
statement instead.
Join the conversation