The Wayback Machine - https://web.archive.org/web/20240928070558/https://www.geeksforgeeks.org/sql-union-all/
Open In App

SQL UNION ALL

Last Updated : 09 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

SQL UNION ALL is a powerful tool used to combine the results of two or more SELECT statements into a single result set. Unlike the UNION operator, which eliminates duplicate records and UNION ALL includes all duplicates. This makes UNION ALL it faster and more efficient when we don’t need to remove duplicates.

SQL UNION ALL Operator

  • The SQL UNION ALL command combines the result of two or more SELECT statements in SQL.
  • For performing the UNION ALL operation, it is necessary that both the SELECT statements should have an equal number of columns/fields, otherwise, the resulting expression will result in an error.

Syntax:

The syntax for the SQL UNION ALL operation is:

SELECT columns FROM table1
UNION ALL
SELECT columns FROM table2;

SQL UNION All vs UNION

Here is the comparison between UNION ALL and UNION Operator:

Feature UNION ALL UNION
Duplicate Records Includes all duplicates Removes duplicate records
Performance Faster, as it doesn’t check for duplicates Slower, as it needs to eliminate duplicates
Use Case When duplicates are acceptable or needed When duplicates need to be removed
Syntax SELECT columns FROM table1 UNION ALL SELECT columns FROM table2; SELECT columns FROM table1 UNION SELECT columns FROM table2;
Memory Usage Generally lower, since no extra processing for duplicates Higher, due to additional steps for duplicate removal
Result Set Combined rows from all SELECT statements, including duplicates Combined rows from all SELECT statements, without duplicates
Applicability Useful for large datasets where performance is critical and duplicates are acceptable Useful when data integrity requires unique records in the result set

Examples of SQL UNION ALL

Let’s look at some examples of the UNION ALL command in SQL to understand its working. First, let’s create a demo SQL database and tables on which UNION ALL will be performed.

Demo SQL Database

In this tutorial on the UNION ALL operator, we will use the following table in examples.

STUDENTS table:

ROLL_NO NAME DOB AGE
1 DEV SHARMA 2001-08-16 17
2 AMAN VERMA 2002-01-04 16
3 KRISH VATSA 2000-11-29 18

TRIP_DETAIL Table:

ROLL_NO NAME DOB AGE
1 DEV SHARMA 2001-08-16 17
2 AMAN VERMA 2002-01-04 16
3 KRISH VATSA 2000-11-29 18
4 VARUN GOYAL 2003-09-21 15

Example 1: Single Field With Same Name

Suppose We want to combine the names from both the STUDENTS and TRIP_DETAIL tables, including all names, even if there are duplicates.

SELECT NAME FROM STUDENTS
UNION ALL
SELECT NAME FROM TRIP_DETAIL;

Output:

NAME
DEV SHARMA
AMAN VERMA
KRISH VATSA
DEV SHARMA
AMAN VERMA
KRISH VATSA
VARUN GOYAL

Explanation: The UNION ALL operator combines all rows from the NAME column in both tables. It includes all names, including duplicates. In this case, “DEV SHARMA”, “AMAN VERMA”, and “KRISH VATSA” appear twice because they exist in both tables.

Example 2: Different Field Names

Suppose We want to combine the ROLL_NO from both tables and align the column names for consistency.

Query:

SELECT ROLL_NO AS Identifier FROM STUDENTS
UNION ALL
SELECT ROLL_NO AS Identifier FROM TRIP_DETAIL;

Output:

Identifier
1
2
3
1
2
3
4

Explanation: Here, ROLL_NO from both tables is selected and aliased as Identifier. The UNION ALL operator combines all roll numbers from both tables, including duplicates. Each ROLL_NO from STUDENTS appears twice because it also exists in TRIP_DETAIL.

Important Points About SQL UNION All

  • UNION ALL command helps us to combine results of two or more SELECT statements from different tables.
  • The UNION ALL command includes the duplicate records from the SELECT statements whereas the UNION command does not include duplicate records otherwise both the commands are same.
  • For performing the UNION ALL operation, it is necessary that both the SELECT statements should have equal number of columns otherwise the resulting expression will result in an error.

Conclusion

The UNION ALL operator is a powerful tool for combining results from multiple queries while preserving all rows, including duplicates. It is particularly useful when you need to aggregate data from similar sources or when duplicates are not a concern. The examples provided illustrate how UNION ALL works with columns of the same and different names.

FAQs

Can UNION ALL be used with different data types?

No, the columns being combined with UNION ALL must have compatible data types. If they differ, you may need to cast or convert the data types to make them compatible.

How does UNION ALL handle NULL values?

UNION ALL will include NULL values in the result set. If NULL values exist in the result sets of the queries being combined, they will appear in the final result set.

Can UNION ALL be used with more than two tables?

Yes, UNION ALL can combine results from more than two SELECT queries. You can chain multiple SELECT queries with UNION ALL to aggregate data from several sources.



Previous Article
Next Article

Similar Reads

UNION vs UNION ALL in SQL
SQL UNION and UNION ALL operators are used to concatenate results of multiple SELECT statements. However, they are different from each other. One key difference between UNION and UNION ALL in SQL is that the UNION command removes duplicates from the final results set, whereas the UNION ALL command allows duplicates in the results set. Here we will
6 min read
Union and Union All in MS SQL Server
In MS SQL Server, the UNION and UNION ALL operators are used to combine the result sets of two or more SELECT statements into a single result set. This allows you to retrieve data from multiple tables or views and combine it into a single dataset. The primary difference between UNION and UNION ALL is that UNION removes duplicate rows from the resul
2 min read
PL/SQL UNION ALL Operator
In PL/SQL, the UNION ALL operator is a powerful tool that allows us to combine the results of two or more SELECT queries into a single result set. Unlike the UNION operator, which eliminates duplicate rows, UNION ALL includes all rows, including duplicates. This makes it faster and more efficient when we need to retain all records from the combined
4 min read
SQL Full Outer Join Using Left and Right Outer Join and Union Clause
An SQL join statement is used to combine rows or information from two or more than two tables on the basis of a common attribute or field. There are basically four types of JOINS in SQL. In this article, we will discuss FULL OUTER JOIN using LEFT OUTER Join, RIGHT OUTER JOIN, and UNION clause. Consider the two tables below: Sample Input Table 1: Pu
3 min read
SQL Full Outer Join Using Union Clause
In this article, we will discuss the overview of SQL, and our main focus will be on how to perform Full Outer Join Using Union Clause in SQL. Let's discuss it one by one. Overview :To manage a relational database, SQL is a Structured Query Language to perform operations like creating, maintaining database tables, retrieving information from the dat
3 min read
SQL UNION Operator
SQL UNION operator combines result sets of two or more SELECT statements into one results set. UNION Operator in SQL The UNION operator in SQL is used to combine the result set of multiple SELECT statements and return one result set. There are some rules for using the SQL UNION operator. Rules for SQL UNION Each table used within UNION must have th
3 min read
PL/SQL UNION Operator
In PL/SQL (Procedural Language/Structured Query Language), the UNION operator is one of the most commonly used set operators. It combines the result sets of two or more SELECT statements into a single result set while removing any duplicate rows. In this article, We will learn about PL/SQL UNION Operator with the help of examples and so on. PL/SQL
3 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQLite Union All Operator
SQLite is a server-less database engine written in C programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is escaping complex database engines like MYSQL etc. It has become one of the most popular database engines as we use it in Television, Mobile Phones, Web browsers, and many more. It is
6 min read
Union All Operator in MariaDB
In MariaDB, the Union All operator is a useful tool for combining results from multiple SELECT queries into a single result set. Unlike the Union operator, Union All retains all rows, including duplicates, making it ideal for merging large datasets efficiently. Whether we are consolidating information from different tables or simplifying complex qu
4 min read
MySQL UNION ALL Operator
The UNION ALL operator in MySQL combines the result sets of multiple SELECT statements by retaining all duplicate rows for improved performance and efficiency. It is particularly useful when complete data inclusion, including duplicates is required. In this article, We will learn about the MySQL UNION ALL Operator by understanding various examples
4 min read
SQLite Union Operator
SQLite is a server-less database engine and it is written in c programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is to escape from using complex database engines like MYSQL etc. It has become one of the most popular database engines as we use it in Television, Mobile Phones, web browsers,
5 min read
Union Operator in MariaDB
MariaDB is an Open-Source Database system and MariaDB offers similar security features to MySQL, including access control, user authentication, and encryption. UNION operator is a fundamental part of MariaDB, a well-known database syste­m. The UNION operator merge­s results from different SELECT que­ries. In this article, We will understand the Uni
5 min read
MySQL UNION Operator
Database management is an important concept of handling and organizing data effectively. One powerful Operator in MySQL for combining results from multiple queries is the UNION operator. This operator allows you to merge the results of two or more SELECT statements into a single result set, eliminating duplicate rows by default. In this article, we
4 min read
SQL Server Query to Find All Permissions/Access for All Users in a Database
In SQL databases, managing and auditing user permissions is crucial for ensuring security and proper access control. To find out what permissions or access levels are granted to users within a database, we can use built-in functions such as sys.fn_my_permissions and sys.fn_builtin_permissions. These functions help administrators and database manage
3 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
Dynamic SQL in SQL Server
In SQL Server, at times the SQL Queries need to be dynamic and not static, meaning the complete SQL query may be built dynamically at run time as a string using the user inputs and any specific application logic. This can be done in queries run from back-end applications or inside stored procedures. In this article let us look into the details abou
6 min read
Dynamic SQL and Temporary Tables in SQL Server
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Data Manipulation Language in SQL. In this article l
6 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
SQL Quiz : Practice SQL Questions Online
This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things interesting and challenging. Whether you're a beginner l
3 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced
SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confidence in handling different database tasks. So, in
15+ min read