Database Tutorial

Course Tutorial Site

Site Admin

Set Operators

with 3 comments

Set operators in SQL are like joins but different. That’s because set operations like the INTERSECT, MINUS, and UNION operators join the results of two queries based on a match, exclusion, or duplicate elimination respectively. A fourth set operator returns the unique rows plus two copies of any duplicate rows, and it is the UNION ALL operator. More or less they’re qualified as follows:

INTERSECT
An INTERSECT operates on two queries that return select lists that share the exact position, number of columns, and data types. An INTERSECT operator returns the rows from both queries that share the same values in all of the select list columns.
MINUS
A MINUS operates like the INTERSECT operator in that both queries must share select lists that match by position, number of columns, and data types. The difference is that the any rows from the first query found in the second query are removed from the result set.
UNION
A UNION acts like a union operator in set mathematics. It returns the unique set of rows found in the collection of both queries. It calculates the distinct set of rows by performing a sort operation that eliminates duplicates. Like the other set operators, the UNION requires that both queries return the same, position, number of columns, and data types.
UNION ALL
A UNION ALL takes all rows returned by one query and adds the rows returned by another query. It does not filter out duplicate rows. It is most useful when both queries return unique sets because it avoids a sorting operation. Like the other set operators, the UNION requires that both queries return the same, position, number of columns, and data types.

The following scrollable list exams the four set operator. They’re defined in the ANSI SQL:89 definition and work with either the Oracle Proprietary outer join or the ANSI SQL:92 style outer joins.

Written by michaelmclaughlin

January 17th, 2010 at 10:28 pm

Posted in

3 Responses to 'Set Operators'

Subscribe to comments with RSS or TrackBack to 'Set Operators'.

  1. THX 🙂

    paul

    8 Mar 13 at 7:31 am

  2. When is a set operator necessary? It seems that, with the exception of minus, all of the set operators accomplished the tasks that Joins already did.

    James

    7 Feb 14 at 6:28 pm

  3. James, When you want the product of two queries that return the same record structure but arrive at the data set through different joins, the UNION, UNION ALL, and INTERSECT are very useful. The UNION works when the sets may have overlapping return sets. The UNION ALL works when the sets will never have overlapping return sets. The INTERSECT works when you only want the overlapping return set. Hope that answers your question.

    michaelmclaughlin

    18 Mar 14 at 11:01 am

Leave a Reply