UNION vs. UNION ALL in SQL Server: What's the Difference?
SQL UNION operator definition
In SQL, the UNION clause combines the results of two or more SELECT statements into a distinct single result set without returning any duplicate rows. In other words, SQL UNION operator concatenates the results of two queries and removes duplicate values.
Fundamental rules for using UNION
- The number of columns in all queries combined by UNION must be the same.
- The order of the columns in all queries combined by UNION must be the same.
- The data types in the columns combined by using UNION must be compatible.
- The number of expressions in all queries combined by UNION must be the same.
Basic syntax of the SQL UNION
Let's look at how UNION functions in SQL. The syntax for it is as follows:
SELECT column_1, column_2, ... column_n FROM table_1 UNION SELECT column_1, column_2, ... column_n FROM table_2 ... UNION SELECT column_1, column_2, ... column_n FROM table_N;