The difference between Union vs Union all is that Union all will not eliminate duplicate rows, instead, it just pulls all rows from all tables fitting your query specifics and combines them into a table. A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

UNION: The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.

UNION ALL: The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.

Example:
Table 1: First, Second, Third, Fourth, Fifth
Table 2: First, Second, Fifth, Sixth

Result Set:
UNION: First, Second, Third, Fourth, Fifth, Sixth (This will remove duplicate values)
UNION ALL: First, First, Second, Second, Third, Fourth, Fifth, Fifth, Sixth, Sixth (This will repeat values)

You should read this, How to quickly search for data all over SQL database.

Union vs Union All – Which is better for performance?

The article was published on October 21, 2019 @ 9:38 AM

Leave a Comment