SQL INSERT INTO SELECT Statement
Last Updated :
11 Dec, 2024
In SQL, the INSERT INTO
statement is used to add or insert records into the specified table. We use this statement to insert data directly into a table by specifying column names in a specific order. The SELECT
statement is used to retrieve data from the table, and it can be used in conjunction with the INSERT INTO
statement to insert data from one table into another.
In this article, we will learn how to use the INSERT INTO
statement along with the SELECT
statement, exploring various examples and their respective explanations. We will also see how it can be used in real-world scenarios.
SQL INSERT INTO SELECT Statement
In SQL, the INSERT INTO SELECT Statement is used to insert data into the table directly. The data which is inserted is the result we get from the SELECT statement. This statement is generally used when we want to copy some data from one table to another. There is a thing to remember, the data returned by the SELECT statement must be compatible with other table columns on which we try to insert them. Otherwise, it will throw us an error.
Syntax
INSERT INTO table_01 (column_01, column_02,.....................)
SELECT (column_01, column_02,.....................)
FROM table_02;
Examples of INSERT INTO SELECT Statement
Before proceeding to examples, Let's first create two tables in our database to serve as the source and destination for our INSERT INTO SELECT statement examples. These tables will contain sample data to illustrate how the statement works effectively.
Table 1: geeksforgeeks
CREATE TABLE geeksforgeeks(
id int PRIMARY KEY,
name varchar(100),
potd int
);
Table 2: users
CREATE TABLE users(
id int PRIMARY KEY,
name varchar(100),
courses int,
rank int,
potd int
);
Next, we insert some sample data into our users
table:
INSERT INTO users(id,name,courses,rank,potd)
VALUES(100,'Vishu',10,15,256);
INSERT INTO users(id,name,courses,rank,potd)
VALUES(101,'Neeraj',5,16,250);
INSERT INTO users(id,name,courses,rank,potd)
VALUES(102,'Aayush',20,17,200);
INSERT INTO users(id,name,courses,rank,potd)
VALUES(103,'Sumit',15,18,210);
INSERT INTO users(id,name,courses,rank,potd)
VALUES(104,'Harsh',25,19,150);
Step 1: Displaying Data in users
Table
SELECT * FROM users;
Output
Users TableExample of SQL INSERT INTO SELECT Statement
The SQL INSERT INTO SELECT statement allows us to copy data from one table into another directly. This can be useful when we want to quickly populate a new table with data that meets certain criteria from an existing table. Below, we provide examples to illustrate how this statement can be used effectively.
Example 1: INSERT INTO SELECT Statement Without Using WHERE Clause.
In this example, we are copying all columns from the "users" table to the "geeksforgeeks" table without applying any filters, allowing us to create an exact replica of the "users" table in "geeksforgeeks".
Query
INSERT INTO geeksforgeeks(id,name,potd)
SELECT id, name, potd
FROM users;
SELECT * FROM geeksforgeeks;
Output
GeeksforGeeks TableExplanation:
We can observe that all the data from the fields id, name, potd are copied from users table and inserted into our table geeksforgeeks. As we have specified no conditions, therefore all the data from users table gets copied to the geeksforgeeks table.
Example 2: INSERT INTO SELECT Statement With Using WHERE Clause
Here, we'll demonstrate how to use the INSERT INTO SELECT
statement with a WHERE clause to filter and insert specific records from one table into another based on certain conditions. This allows us to selectively copy data from the source table to the destination table based on defined criteria.
Case 1: WHERE Clause in potd Column
In this case, we will insert all those values from the users table to our geeksforgeeks table where the potd score is greater or equal to 210.
Query:
INSERT INTO geeksforgeeks(id,name,potd)
SELECT id, name, potd
FROM users WHERE potd>=210;
Output
id | name | potd |
---|
100 | Vishu | 256 |
101 | Neeraj | 250 |
102 | Aayush | 200 |
Explanation:
In the above displayed image we can observe that in this geeksforgeeks table, no values in potd column are less than 210. Thus all the values from users table gets copied to our geeksforgeeks table where potd score is greater than or equal to 210.
Case 2: WHERE Clause in Courses and Rank Columns
In this case, we will insert all those values from users table to our geeksforgeeks table where the courses taken is greater or equal to 10 and rank should be less than or equal to 18.
Query:
INSERT INTO geeksforgeeks(id,name,potd)
SELECT id, name, potd
FROM users WHERE courses>=10 AND rank<=18;
Output
id | name | potd |
---|
100 | Vishu | 256 |
102 | Aayush | 200 |
103 | Sumit | 210 |
Explanation:
From the above output, we can observe that all those values from users table where courses acquired are grater than or equal to 10 and where rank obtain is less than or equal to 18 are inserted into our geeksforgeeks table. We can clarify this by matching the values of geeksforgeeks table with the values of users table.
Case 3: WHERE Clause With NOT IN Statement
In this case, we will use WHERE Clause along with NOT IN statement. We will insert all those data from users table where potd score is greater than 200 and ID should not be equal to '103', or '104'.
Query:
INSERT INTO geeksforgeeks(id,name,potd)
SELECT id, name, potd
FROM users WHERE potd > 200 AND ID NOT IN (103,104);
Output
id | name | potd |
---|
100 | Vishu | 256 |
101 | Neeraj | 250 |
Explanation:
In the above image, we can observe that all those values from users table get inserted into geeksforgeeks table which satisfies both the conditions i.e. potd score should be greater than 200 and ID should be equal to either 103 or 104.
Conclusion
In SQL, INSERT INTO SELECT Statement is generally used to copy data from one table to some other table. We can also filter out the first table's data before inserting it into another table with the help of WHERE Clause. Thing to keep in mind while copying data from one table to another, is that data of the first table should be compatible with the data types of another table. Otherwise, this will throw us an error. In this article, we have covered all the concepts will clear and concise examples along with their respective explanations.
Similar Reads
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read