Use INSERT INTO target_table (col1, col2, ...) SELECT expr1, expr2, ... FROM source_table WHERE ... to copy rows returned by a SELECT query into an existing table. Matching column counts, compatible data types, and explicit column lists prevent positional bugs and schema drift errors.
1. Basic INSERT INTO ... SELECT (Explicit Columns)
Always list target columns explicitly so column order stays clear even if the table schema changes later.
INSERT INTO active_customers (customer_id, full_name, email, created_at)
SELECT
id,
full_name,
email,
created_at
FROM customers
WHERE status = 'ACTIVE';
- The number and order of expressions in
SELECTmust match the columns listed inINSERT INTO. - Data types must be compatible or castable to the destination columns.
2. Transform Data and Join Tables During Insert
Because the source is a full SELECT query, you can filter rows, join tables, compute expressions, or apply functions before inserting.
INSERT INTO monthly_sales_summary (department_id, sales_month, total_revenue, order_count)
SELECT
o.department_id,
DATE_TRUNC('month', o.order_date) AS sales_month,
SUM(o.amount) AS total_revenue,
COUNT(*) AS order_count
FROM orders AS o
WHERE o.status = 'PAID'
AND o.order_date >= DATE '2026-11-01'
AND o.order_date < DATE '2026-12-01'
GROUP BY
o.department_id,
DATE_TRUNC('month', o.order_date);
3. Avoid Duplicate Rows When Copying Data
If the destination table has a unique constraint or you want to skip records that already exist, filter with NOT EXISTS or LEFT JOIN (or use dialect-specific upsert/conflict handling where supported).
INSERT INTO newsletter_subscribers (email, subscribed_at)
SELECT
u.email,
CURRENT_TIMESTAMP
FROM users AS u
WHERE u.marketing_opt_in = TRUE
AND NOT EXISTS (
SELECT 1
FROM newsletter_subscribers AS ns
WHERE ns.email = u.email
);
4. Safe Workflow Before Running the Insert
- Run the
SELECTfirst: Execute theSELECTquery on its own to inspect row counts,NULLvalues, and calculated columns before inserting. - Watch identity / auto-increment columns: Omit
IDENTITYorSERIALprimary key columns from theINSERTcolumn list unless you intentionally insert explicit IDs and your database allows it. - Use a transaction for large or sensitive loads: Wrap
INSERT INTO ... SELECTinside a transaction (BEGIN/COMMIT/ROLLBACK) so you can verify row counts before finalizing.
You must log in or register to comment.
