SQL beginner insert select data-management

How to Insert Rows Using SELECT in SQL?

Insert Select SQL Statement is a SQL query that this sql statement inserts rows into a target table by selecting data from a source table.. Formula Genius generates and validates this formula automatically from a plain-English prompt.

Inserting data from one table to another can streamline data management and enhance efficiency. This guide explains how to use the INSERT INTO ... SELECT statement.

The Formula

Prompt

"Insert rows into a table by selecting from another table using INSERT INTO ... SELECT"

SQL
INSERT INTO target_table (column1, column2) SELECT column1, column2 FROM source_table;

This SQL statement inserts rows into a target table by selecting data from a source table.

Step-by-Step Breakdown

  1. Specify the target table where data will be inserted.
  2. List the columns in the target table that will receive the data.
  3. Use the SELECT statement to retrieve data from the source table.
  4. Ensure the selected columns match the target columns in data type and order.

Edge Cases & Warnings

  • Inserting data when the source table is empty results in no new rows.
  • Data type mismatches between source and target columns can cause errors.
  • Inserting duplicate rows if the target table has unique constraints.
  • Selecting from a view instead of a table may lead to unexpected results.

Examples

Prompt

"INSERT INTO employees (name, age) SELECT name, age FROM new_hires;"

SQL
Rows from new_hires are inserted into employees.
Prompt

"INSERT INTO orders (product_id, quantity) SELECT product_id, quantity FROM pending_orders;"

SQL
Rows from pending_orders are inserted into orders.

Frequently Asked Questions

Can I insert data into multiple tables at once?

No, you can only insert into one table at a time using this method.

What happens if the source table has no matching rows?

No rows will be inserted into the target table.

Can I use JOIN in the SELECT statement?

Yes, you can join multiple tables in the SELECT statement to insert combined data.

Can't find what you need?

Describe any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.