Set Operators

I am going to promote my series of very short articles or tidbits on Transaction SQL Operators. An operator is a symbol specifying an action that is performed on one or more expressions.

I will exploring the Set Operators today. A Venn diagram is used to express different operations between sets. The above image represents the four possible operations given two sets, A and B, and three operators. We will get into the operators supported by Microsoft Transaction SQL shortly.

To demonstrate these operators, we need a two temporary tables to query against. The TSQL code below will create temporary tables A and B.

The UNION operator combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union. By default, the operator removes any duplicates. Using set notation, the A ∪ B notation is the union of both data sets in the above diagram.

To use this operator, the number and order of the columns have to be the same as well as the data types of the columns must be compatible.

Using the ALL clause of the UNION operator shows the all rows including the duplicates. Please note that the order of the rows in the result set is not guaranteed. In our example, both values 5 and 6 are duplicated in the output list.

The EXCEPT operator returns any distinct values from the left query that are not also found on the right query. Using set notation, A – B is the EXCEPT operation of set A in regards to B. Again, the number and order of the columns have to be the same as well as the data types of the columns must be compatible.

Since this operator is order specific, the set notion B – A is the EXCEPT operation of set B in regards to A. Please see the image above for a visual representation using set theory.

Last but not least, the INTERSECT operator returns any distinct values in common from both the left and right queries.

Using set notation, A ∩ B is the INTERSECT operation between sets A and B. As usual, the number and order of the columns have to be the same as well as the data types of the columns must be compatible.

To wrap-up this article, set operators are a great way to combine two similar query outputs using the UNION, EXCEPTION or INTERSECTION as combinatorial rules. Next time, I will be researching the String Operators.

Related posts

Leave a Comment