Langsung ke konten utama

Difference: SQL UNION vs UNION ALL?

 

Difference: SQL UNION vs UNION ALL ?

UNION and UNION ALL are both used to retrieve records from multiple tables. This article will detail the differences between the two, allowing you to make the best choice for each unique scenario.

You can use SQL’s UNION and UNION ALL commands to get data from multiple tables in your database. It’s a common use case, considering that most databases have many tables. Both UNION and UNION ALL are known as set operators. In SQL, set operators combine the results of two or more queries into a single result. You can read more about set operators in this article.

When comparing UNION vs. UNION ALL, there is one major difference:

  • UNION only returns unique
  • UNION ALL returns all records, including duplicates.

If you feel like you would benefit from a well-structured, comprehensive course that covers foundational SQL, consider this SQL Basics course from LearnSQL.

UNION vs. UNION ALL: Syntax

The syntax of both UNION variants is very similar. Let’s look at them individually, starting with UNION.

UNION Syntax

Remember, UNION combines the result set of two or more SELECT statements, showing only distinct values.

The SQL syntax below shows a UNION occurring between two different tables; the columns in both SELECT statements are of the same or matching data types.

The WHERE clause shown is an optional inclusion:

SELECT column_1, column_2
FROM table_1
[WHERE condition]
 
UNION
 
SELECT column_1, column_2
FROM table_2
[WHERE condition]

SQL UNION ALL Syntax

Remember, UNION ALL combines the results of two or more SELECT statements, showing all values, including duplicates if they exist.

The SQL syntax below shows a UNION ALL occurring between two different tables. Once again, the columns in the SELECT are of the same or matching data types and the WHERE clause is optional:

SELECT column_1, column_2
FROM table_1
[WHERE condition]
 
UNION ALL
 
SELECT column_1, column_2
FROM table_2
[WHERE condition]

SQL UNION and UNION ALL Explained

There are several usage rules for UNION and UNION ALL. Failure to adhere to these rules will result in error messages:

  • The number of columns used in your first query and your second query must be the same and the data types (e.g. INT, VARCHAR, etc.) must match.
  • The column names included in both queries can differ; when this is the case, the resulting dataset will show the column names from the first query.
  • When using SQL aliases in conjunction with UNION and UNION ALL, you only need to include the alias with the first query. Including it with the second query will not cause an error, but it will also have no impact on the output.

You can use UNION and UNION ALL to combine tables that do not have any columns in common. This use case is covered in this article on how to join tables without a common column.

LearnSQL.com provides a comprehensive learning experience when it comes to learning SQL. With 30 interactive courses at various levels, the platform will help you to learn the skills you need to tackle reporting in SQL with confidence.

SQL UNION vs UNION ALL: Example

Let’s look at a practical example to gain greater understanding of UNION vs. UNION ALL. Imagine we have a database with information on several clubs. Each table will show the members of that club and what location they attend. Each club may have several different branches or locations where they meet. The first table is for the book_club. It contains the name of club members and what location they attend:

namelocation
JohnFair Street
MaryFair Street
PaulWest Street

Similarly, the rowing_club contains the name of club members and what location they attend.

namelocation
MaryFair Street
SamanthaFair Street
PaulWest Street

Now that we have our tables, let’s write our SQL query. Using the UNION syntax, we get the following query:

SELECT name, location
FROM book_club
 
UNION
 
SELECT name, location
FROM rowing_club

UNION first performs a sorting operation and eliminates the records that are duplicated across all columns before finally returning the combined data set. You can see that we use columns of the same data type and SELECT the same number of columns in each query. This follows the rules of using UNION and should execute without an error.

Running this query produces the following result:

namelocation
JohnFair Street
MaryFair Street
PaulWest Street
SamanthaFair Street

There we have it! All of the members from both clubs!

Want to learn SQL? Check out our SQL From A to Z track!

Now let’s alter the query and change UNION to UNION ALL:

SELECT name, location
FROM book_club
 
UNION ALL
 
SELECT name, location
FROM rowing_club

With UNION ALL in place, we can expect the results to include duplicates. Let’s execute this new query and observe the output:

namelocation
JohnFair Street
MaryFair Street
PaulWest Street
MaryFair Street
SamanthaFair Street
PaulWest Street

Can you spot all of the duplicate records? Compare this output to our original two tables. You can see that every row was included.

UNION or UNION ALL – Which Should You Choose?

Now that you know how to use both UNION and UNION ALL, you’re probably wondering which one is best for your situation. One thing to consider is the fact that UNION removes duplicate records, which can impact the performance of your query.

If you’re wondering which variant to use, remember:

  • Using UNION effectively performs a SELECT DISTINCT on the results set.
  • If you know that all of the records returned by UNION are going to be unique, use UNION ALL; it will be faster. This is especially relevant for larger datasets.

Do you want to learn all the basics of SQL in one place? Go through our SQL From A to Z track!

Write Complex Queries with UNION and UNION ALL

We’ve covered the differences between UNION and UNION ALL and why you might choose one or the other. With this information, you can now retrieve data from two or more tables in your database. Both UNION and UNION ALL play an important role in the use of recursive queries, a more advanced topic that is covered in great detail in our Recursive Queries course.

Don’t forget to bookmark this page so you can have easy access to the explanations and examples of UNION vs. UNION ALL. Also, consider saving this page of our SQL Cookbook, which explains how to combine the results of two queries in SQL. This knowledge can take your SQL queries to the next level, helping you handle complex use cases with ease!

Komentar

Postingan populer dari blog ini

CREATE CROSS TAB QUERY IN MYSQL

MySQL Multi-Aggregated Rows in Crosstab Queries MySQL’s crosstabs contain aggregate functions on two or more fields, presented in a tabular format. In a multi-aggregate crosstab query, two different functions can be applied to the same field or the same function can be applied to multiple fields on the same (row or column) axis. Rob Gravelle shows you how to apply two different functions to the same field in order to create grouping levels in the row axis. Today’s topic of discussion is crosstabs, which contain multiple aggregate functions in the row axis of a tabular resultset. Recall from the the  All About the Crosstab Query  article that an aggregate function is one that summarizes a group of related data in some way. Examples of aggregate functions include COUNT, SUM, AVG, MIN, and MAX. In a multi-aggregate crosstab query, two different functions can be applied to the same field or the same function can be applied to two or more fields. Today we’ll create a query...

Mengatasi "This app can’t run on your PC Windows 10"

  Salah satu pesan error yang sering muncul saat aplikasi tidak bisa dibuka di Windows 10 adalah “ This app can’t run on your PC ,   to find a version for your PC check with the software publisher “. Masalah seperti ini cukup umum dan dialami banyak orang, terutama saat menjalankan aplikasi yang bukan dari Microsoft. Penyebab utama terjadinya masalah ini adalah karena masalah kompatibilitas antara aplikasi dengan versi Windows yang dianggap tidak sesuai oleh sistem. Bisa juga karena aplikasi atau game yang akan jalankan tersebut terkena filter oleh Windows sehingga prosesnya diblokir. Windows 10 memiliki fitur untuk memblokir aplikasi tidak dikenal yang berasal dari  unverified developers , fitur ini secara default akan aktif dengan tujuan untuk mencegah masuknya aplikasi yang mengandung malware dan virus. Penyebab lainnya bisa juga karena file aplikasi yang rusak, file sistem yang korup, atau masalah yang disebabkan oleh malware dan virus. Pada kesempatan kali ini  ...

Linux Basic Command Cheat Sheet

 https://www.guru99.com/linux-commands-cheat-sheet.html Linux Command Cheat Sheet In this Linux/Unix command line cheat sheet, you will learn: Basic Linux commands File Permission commands Environment Variables command User management commands of linux Networking command Process command VI Editing Commands Basic Linux commands Command Description ls Lists all files and directories in the present working directory ls -R Lists files in sub-directories as well ls -a Lists hidden files as well ls -al Lists files and directories with detailed information like permissions,size, owner, etc. cd or cd ~ Navigate to HOME directory cd .. Move one level up cd To change to a particular directory cd / Move to the root directory cat > filename Creates a new file cat filename Displays the file content cat file1 file2 > file3 Joins two files (file1, file2) and stores the output in a new file (file3) mv file "new file path" Moves the files to the new location mv filename new_file_name Re...