GAZAR

Principal Engineer | Mentor

What is the difference between UNION and UNION ALL?

What is the difference between UNION and UNION ALL?

In SQL, both the UNION and UNION ALL operators are used to combine the results of two or more SELECT statements into a single result set. However, they have distinct behaviors that differentiate them from each other. Let's explore the difference between UNION and UNION ALL with examples.

The UNION operator is used to combine the results of two or more SELECT statements into a single result set, removing any duplicate rows from the final result. It effectively performs a set union operation on the result sets of the individual SELECT statements.

SELECT name FROM employees
UNION
SELECT name FROM contractors;

The UNION ALL operator, on the other hand, is used to combine the results of two or more SELECT statements into a single result set without removing duplicate rows. Unlike UNION, it does not perform any duplicate elimination and simply concatenates the result sets of the individual SELECT statements.

SELECT name FROM employees
UNION ALL
SELECT name FROM contractors;

This query will combine the results of the two SELECT statements and return a single result set containing all names from both tables, including duplicates.

Summary:

  • UNION: Combines the results of multiple SELECT statements into a single result set, removing duplicate rows.
  • UNION ALL: Combines the results of multiple SELECT statements into a single result set without removing duplicate rows.

Understanding the distinction between UNION and UNION ALL is crucial for performing set operations in SQL and obtaining the desired result set based on specific requirements.


Comments