Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

INSERT INTO SELECT



The SQL INSERT INTO SELECT Statement


The INSERT INTO SELECT statement in SQL is used to insert data into a table from the result of a SELECT query. This is useful when you want to copy data from one table into another, or when you want to populate a table with data from a query result.

Here's the basic syntax of the INSERT INTO SELECT statement:


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


Example:

Let's say we have a table named customers with columns customer_id, first_name, last_name, and email, and we want to create a new table important_customers and insert data into it from customers where the email domain is 'example.com':


            CREATE TABLE important_customers (
                customer_id INT,
                first_name VARCHAR(50),
                last_name VARCHAR(50),
                email VARCHAR(100)
            );
            
            INSERT INTO important_customers (customer_id, first_name, last_name, email)
            SELECT customer_id, first_name, last_name, email
            FROM customers
            WHERE email LIKE '%@example.com';
        

This will insert rows into the important_customers table, copying the data from the customers table but only for customers whose email addresses end with '@example.com'.

It's important to ensure that the column types and order in the SELECT query match the column types and order in the INSERT INTO clause to avoid any errors. Additionally, make sure that the target table is properly structured to accommodate the data being inserted



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java