Query
Suppose a working table with three compatible columns already exists:
CREATE TABLE customers_london (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
city TEXT NOT NULL
);We can fill it from customers without typing the values in by hand:
INSERT INTO customers_london (id, name, city)
SELECT id, name, city
FROM customers
WHERE city = 'London';The source query returns four rows, and those four rows are inserted. If the WHERE returned none, the statement would insert zero rows.
How INSERT INTO ... SELECT works
Read both lists side by side: the first expression in the SELECT fills the first target column, the second expression fills the second, and so on. Listing the target columns means you do not depend on the physical column order of the table.
The SELECT decides what you try to insert; the target table decides what is valid. A duplicate key, a NOT NULL, a FOREIGN KEY or a CHECK can reject rows even when the source query is correct.
Cases that change the result
You can also transform the data before inserting it
The expressions in the SELECT do not have to be plain copies of columns. You can calculate values, use CASE, apply functions or join tables, as long as the output still fits the target.
INSERT INTO customers_summary (customer_id, name, status)
SELECT id,
name,
CASE WHEN active = 1 THEN 'active' ELSE 'inactive' END
FROM customers;This form separates two jobs: the SELECT builds the rows and the INSERT stores them in the target schema.
Check the SELECT before you change any data
A safe habit is to run only the source query first. Check the number of rows, the columns, the values and any duplicates. Then run the INSERT inside a transaction where the environment and engine allow it.
-- 1. Check exactly which rows the source produces
SELECT id, name, city
FROM customers
WHERE city = 'London';
-- 2. Insert only after validating that output
INSERT INTO customers_london (id, name, city)
SELECT id, name, city
FROM customers
WHERE city = 'London';Do not confuse display order with storage. If you later need to read the rows in a particular order, use ORDER BY in the SELECT that queries the destination table.
Common mix-ups with INSERT INTO ... SELECT
Swapping the meaning of the columns
INSERT INTO customers_london (id, name, city)
SELECT id, city, name
FROM customers;The number of expressions matches, but name and city ended up swapped. SQL cannot work out your intent from the column names.
Forgetting that constraints still apply
If the destination table already contains a id that the SELECT tries to insert again, a primary key or unique constraint may reject the operation. Check for duplicates before loading.
Using INSERT ... SELECT when you only need to query
A permanent copy adds maintenance. If you only need to reuse a result for a while, a CTE, a subquery or a view may express the intent better.