• Home
  • SQL Insert Into Select Statement

    The SQL INSERT INTO SELECT statement allows you to insert data into a table from the result set of a SELECT statement. This is useful when you want to copy data from one table to another or insert data derived from a query. The syntax for the INSERT INTO SELECT statement is as follows:


    sql
    INSERT INTO target_table (column1, column2, ...)
    SELECT column1, column2, ...
    FROM source_table
    WHERE condition;

    - `target_table`: The name of the table where you want to insert the data.
    - `column1, column2, ...`: The specific columns in the target table where you want to insert the data. If omitted, all columns in the target table must match the number and order of columns in the SELECT statement.
    - `source_table`: The table or tables from which you want to select data.
    - `condition`: An optional condition that filters the rows selected from the source table(s).


    Here's an example to illustrate how to use the INSERT INTO SELECT statement:

    sql
    INSERT INTO customers (customer_id, customer_name, email)
    SELECT id, name, email
    FROM temp_customers
    WHERE age > 18;

    In this example, the data from the `temp_customers` table is inserted into the `customers` table. Only the `id`, `name`, and `email` columns are selected from the `temp_customers` table, and the condition `age > 18` filters the rows to be inserted. The corresponding columns in the `customers` table should match the number and order of the selected columns.


    Make sure the data types of the selected columns match the data types of the target columns in the `INSERT INTO` statement to avoid any compatibility issues.

    Note: It's essential to be cautious when using the INSERT INTO SELECT statement as it can affect a significant number of rows and potentially overwrite existing data. Always ensure you have proper backups and test the statement in a safe environment before applying it to production data.


    About the Author



    Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

    We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





     PreviousNext