INSERT with SELECT
- SQL course
- Beginner
- Lesson 74/115
- 4 min
Copy data from another table.
INSERT ... SELECT
With INSERT INTO ... SELECT you copy data chosen from one table into another.
INSERT INTO archive (id, name)
SELECT id, name FROM products
WHERE stock = 0;This query copies out-of-stock products to the archive.
The result of a SELECT query is inserted into archive as new rows. WHERE keeps only the rows where stock = 0 holds.
INSERT ... SELECT — details
SELECT replaces VALUES. The SELECT column count must match the INSERT columns. Ideal for bulk moves.
Practice INSERT ... SELECT
Copy all rows from products into the archive table.
Starter code
-- copy
INSERT INTO archive
SELECTSample solution
INSERT INTO archive (id, name)
SELECT id, name FROM productsExpected output
5 satır eklendi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does INSERT ... SELECT do?
- Copies rows between tables Correct answer
- Deletes rows
- Adds a column
- Drops a table
Explanation: INSERT ... SELECT copies data between tables.
2 Select and insert
INSERT INTO archive (id, name)
____ id, name FROM products;
INSERT INTO archive (id, name)
SELECT id, name FROM products;
Explanation: INSERT INTO … SELECT inserts the result of a query directly into another table.
3 INSERT with SELECT: match the terms
| Term | Meaning |
|---|---|
INSERT |
insert |
SELECT |
select |
INTO |
into |
FROM |
source |