How to Append Two Tables and Put the Result in a Table in SQL?
Last Updated :
18 Dec, 2024
SQL provides the UNION
and UNION ALL
operators to combine data from two tables into a new table. These operators are used to merge rows from multiple tables into a single result set. The UNION
operator removes duplicate rows from the combined result, while UNION ALL
includes all rows, including duplicates.
In this article, we will explain how to use these operators with practical examples and show the output for each method. We will also provide tips and best practices for using UNION
and UNION ALL
effectively in our SQL queries.
Using UNION
to Combine Tables
The UNION
operator combines the results of two SELECT queries into a single result set, excluding duplicates. It merges the data from two tables into one, ensuring that each row in the final table is unique. The syntax for using UNION
is as follows:
Syntax:
SELECT column_one, column_two,..column_N INTO Table_name FROM table_name
UNION SELECT column_one,column_two,column_three,.. column_N FROM table_name;
Suppose we have two departmental stores with data stored in two tables. Shop1 contains products like USB drives, pencils, and water bottles, while Shop2 stocks items such as nail files, rubber bands, and shoes. Each table provides a unique inventory snapshot.
Shop1 Table:
Table Shop1Shop2 Table:
Table Shop2
Query Using UNION
To combine the data from Shop1
and Shop2
into a new table joined
, excluding duplicates. This command merges the data from both tables, showing only unique records in the result set. Run the following command to see the output:
SELECT * INTO joined FROM Shop1
UNION
SELECT * FROM Shop2;
Output
Item_Id | Name | Count |
---|
1 | USB drive | 10 |
1 | nail file | 11 |
2 | pencil | 11 |
2 | rubber band | 10 |
3 | candle | 1 |
4 | pencil | 10 |
4 | sharpie | 19 |
5 | model car | 12 |
6 | water bottle | 12 |
6 | water bottle | 20 |
7 | bread | 3 |
8 | shoes | 19 |
9 | face wash | 20 |
Using UNION ALL
to Combine Tables
The UNION ALL
operator also combines the results of two SELECT queries into a single result set but retains all rows, including duplicates. The difference between Union and Union All is UNION doesn't include duplicates, but UNION ALL includes duplicates too. Both are used with similar syntax. So, the syntax for UNION ALL
is:
Syntax:
SELECT column_one, column_two,column_three,.. column_N INTO Table_name FROM
table_name UNION SELECT column_one, column_two, column_three,..column_N
FROM table_name;
Query Using UNION ALL
:
To create a new table joined2
that includes all rows from Shop1
and Shop2
including duplicates, we use the following SQL command. This command combines the data from both tables and retains all entries, even if they appear in both Shop1 and Shop2.
Query:
SELECT * INTO joined2 FROM Shop1
UNION ALL
SELECT * FROM Shop2;
Output
Item_Id | Name | Count |
---|
1 | USB drive | 10 |
1 | nail file | 11 |
2 | pencil | 11 |
2 | rubber band | 10 |
3 | candle | 1 |
3 | candle | 1 |
4 | sharpie | 19 |
4 | pencil | 10 |
5 | model car | 12 |
5 | model car | 12 |
6 | water bottle | 20 |
6 | water bottle | 12 |
7 | bread | 3 |
8 | shoes | 19 |
9 | face wash | 20 |
Conclusion
Using UNION
and UNION ALL
effectively allows us to merge data from multiple tables into a single table. While UNION
filters out duplicates, UNION ALL
retains all rows. Understanding the difference between these operators helps manage data accurately and efficiently in SQL databases. By using these methods, we can maintain data integrity, avoid errors, and manage complex queries effectively. By mastering the use of UNION
and UNION ALL
,we can easily handle complex data integration tasks, ensuring our SQL queries produce accurate and meaningful results.
Similar Reads
How to Select All Records from One Table That Do Not Exist in Another Table in SQL?
When working with SQL databases, a common requirement is to find records from one table that do not exist in another table. This can be achieved using various SQL techniques like LEFT JOIN, NOT IN, or NOT EXISTS. In this detailed guide, we will explain how to accomplish this using SQL queries and La
4 min read
How to Copy Table to Another Table in SQL
Copying data from one table to another is a common task in SQL whether we are migrating data by creating backups or simply duplicating a table's structure and content for further use. In this article, we'll explore several ways to copy a table to another table in SQL Server including copying both th
3 min read
How to Get the Names of the Table in SQL
Retrieving table names in SQL is a common task that aids in effective database management and exploration. Whether we are dealing with a single database or multiple databases, knowing how to retrieve table names helps streamline operations. SQL provides the INFORMATION_SCHEMA.TABLES view, which offe
3 min read
How to Create One Table From Another Table in SQL
Creating a table based on the structure and data of an existing table is a common task in database management. This process allows us to replicate a table for backup, testing or data transformation purposes. SQL provides efficient methods to create one table from another while preserving the schema,
3 min read
How to Update Two Tables in One Statement in SQL Server?
To update two tables in one statement in SQL Server, use the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both updates simultaneously. Here, we will learn how to update two tables in a single statement in SQL Server.
3 min read
How to Copy Data From One Column to Another in the Same Table in SQL?
Efficiency in data manipulation is crucial while using Structured Query Language (SQL). To manage a wide range of tasks, including organizing, retrieving, updating, and deleting data, SQL provides a comprehensive set of instructions. Among these, copying data between columns in the same table is a c
4 min read
How to Get Counts of all Tables in a Schema in PL/SQL?
In Database Management System, it is essential to retrieve the statistical information about tables with the schema. Whether it is for monitoring the database health, optimizing the performance, or simply understanding the data structures having access to row counts of the tables can be more valuabl
5 min read
How to Show/List Tables in MySQL Database
In MySQL, the SHOW TABLES command is a powerful tool used to list the tables within a specific database. This command provides a convenient way to view the tables that exist in a database without needing to query the database schema directly. In this article, we are going to explore various ways whe
5 min read
How to Update From One Table to Another Based on an ID Match in SQL
In SQL, updating data between tables is a common operation used to maintain data consistency and accuracy across related datasets. Whether we need to synchronize records, update fields, or correct discrepancies, SQL provides efficient methods to achieve this. In this article, we will explain how to
4 min read
How to Update a Table Data From Another Table in SQLite
SQLite is an embedded database that doesn't use a database like Oracle in the background to operate. The SQLite offers some features which are that it is a serverless architecture, quick, self-contained, reliable, full-featured SQL database engine. SQLite does not require any server to perform queri
3 min read