Guide to Oracle SQL (Buffalo State University Version)
Using the Set Operators
Set Operators
The "Set Operators" (UNION, UNION ALL, INTERSECT, and MINUS) are used to work with result sets from two (2) SELECT statements.
Operator
Description
UNION
Returns a sorted and non-duplicate result set from two (2) queries.
UNION ALL
Returns a non-sorted and duplicates included result set of only the rows that occur in each query.
INTERSECT
Returns a sorted and non-duplicate result set from two (2) queries.
MINUS
Returns a sorted and non-duplicate result set from the first query that do no occur in the result set of the second query.
Figure 9-1: SQL "Set" Operators
Classifications and The Venn Diagram
Let's look at a company's employees and customers example. Both are members of the people classification (set). Employess can also be customers which are identified in the next figure where the inner circles (classifications) overlap. This is where they INTERSECT. The UNION of these three sets are all three (3) circles. The MINUS sets would be employees who are not customers and customer who are not employees.
Some Set Operator Principles
You must have two (2) or more SELECT queries to use a set operator. Each Select statement must have the same number or fields being returned in its result set. They do not have to have the same field names. The fields need to be of the same data type group (NUMBER/INTEGER, DATE/TIMESTAMP, for example). Since UNION, INTERSECT, and MINUS will sort the result set (and remove duplicates) you cannot have an ORDER BY clause in each SELECT statement. You can change the sorting by using a single ORDER BY at the end of the compound SELECT query.
Some Complex Set Operator Examples
If the SELECT statements do not have to have the same number of fields you can generate the additional fields using a NULL value. Remeber that the field data types must be in the same groups. So, if you are generating a string us TO_CHAR(NULL) and if you are generating a number us TO_NUMBER(NULL).
The Order of a Complex Set Operator Matters
The order of your SELECT statements is important. SQL will execute the statements in the order they are presented. You can use parentheses, () around your SELECT queries to change this order of precedence.