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.ย 

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

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

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:

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:

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.

Did you learn anything from this article? Leave a comment below!

Leave a Comment