In this article, we will be focusing on Working of SQL INSERT INTO SELECT statement altogether.


What is SQL SELECT statement?

SQL SELECT query displays the specified data from the table of a database.

Syntax:

We can either display all the data or a portion of it engrossed by conditions.

Example:


What is SQL INSERT statement?

SQL INSERT query is useful in inserting records into the database according to the specified columns and conditions.

Syntax:


Working of SQL INSERT INTO SELECT statement

SQL INSERT INTO SELECT statement enables us to select and copy data from one table to another.

Syntax:

This statement executes in the following manner:

  • Initially, it selects data from the specified columns of the table1.
  • Further, the selected data from the columns of table1 is inserted into the specified columns of table2

Thus, by using INSERT INTO SELECT, we can copy some particular data from a table and insert it into another table.

The existing data values of table1 and table2 does not get affected by the INSERT INTO SELECT query.

Having understood the working of the INSERT INTO SELECT query, let us now understand the syntax of the same in the below section.


Implementing INSERT INTO SELECT through examples

Initially, we create a Table 1 — ‘Info’ using SQL Create query with the following columns:

Then, we insert records into the table 1 — ‘Info’ using SQL Insert query.

Output: Table 1 — ‘Info’

SQL-INSERT-INTO-SELECT-Table-1

INSERT INTO SELECT Table 1

Further, we create Table 2 – ‘Wholesale’ with the following data columns:

  • Object_id
  • Price
  • Quantity
  • City

The data values into ‘Wholesale’ are inserted using INSERT query of SQL.

Output: Table 2 — ‘Wholesale’

INSERT INTO SELECT Table 2

Now, In this example, we execute the SQL INSERT INTO SELECT query to perform the following–

  1. select the data values of the column ‘Price’ and ‘City’ from ‘Info’
  2. insert and copy the above-selected records under the column ‘Price’ and ‘City’ of the ‘Wholesale’ table.

Output:

SQL-INSERT-INTO-SELECT

INSERT INTO SELECT example 1

In this example, we have selected and copied all the data values from the table ‘Info’ and inserted it into the table ‘Wholesale’.

Note: The data values are copied from table 1 to table 2. But the original data values of the table(from which the data is being copied) remain unaltered.

Output:

SQL INSERT INTO SELECT Example 2

Conclusion

By this, we have come to the end of this topic. The INSERT INTO SELECT query can be further used alongside different clauses such as WHERE clause, GROUP BY clause, etc. I recommend you to try these out.

For more posts related to SQL, please do visit SQL JournalDev.

And feel free to comment below in case, you come across any doubt!


References

By admin

Leave a Reply

%d bloggers like this: