How do you use INSERT INTO ... SELECT FROM to copy query results into a table in SQL | A1Lab@HumairaM to SQLEnglish • 2 days ago

How do you use INSERT INTO ... SELECT FROM to copy query results into a table in SQL

message-square
0

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 SELECT must match the columns listed in INSERT 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

  1. Run the SELECT first: Execute the SELECT query on its own to inspect row counts, NULL values, and calculated columns before inserting.
  2. Watch identity / auto-increment columns: Omit IDENTITY or SERIAL primary key columns from the INSERT column list unless you intentionally insert explicit IDs and your database allows it.
  3. Use a transaction for large or sensitive loads: Wrap INSERT INTO ... SELECT inside a transaction (BEGIN / COMMIT / ROLLBACK) so you can verify row counts before finalizing.