Set Operations
The SQL operations union, intersect, and except operate on
relations and correspond to the mathematical set-theory operations ∪,
∩, and −.
• The set of all courses taught in the Fall 2009 semester:
select course_id
from section
where semester = ’Fall’ and year= 2009;
• The set of all courses taught in the Spring 2010 semester:
select course_id
from section
where semester = ’Spring’ and year= 2010;
The Union Operation
To find the set of all courses taught either in Fall 2009 or in Spring
2010, or both, we write:
(select course_id
from section
where semester = ’Fall’ and year= 2009)
Union
(select course_id
from section
where semester = ’Spring’ and year= 2010);
The union operation automatically eliminates duplicates, unlike the
select clause.
If we want to retain all duplicates, we must write union all in place
of union:
(select course_id
from section
where semester = ’Fall’ and year= 2009)
union all
(select course_id
from section
where semester = ’Spring’ and year= 2010);
The Intersect Operation
To find the set of all courses taught in the Fall 2009 as well as in
Spring 2010 we write:
(select course_id
from section
where semester = ’Fall’ and year= 2009)
intersect
(select course_id
from section
where semester = ’Spring’ and year= 2010);
If we want to retain all duplicates, we must write intersect all in
place of intersect:
(select course_id
from section
where semester = ’Fall’ and year= 2009)
intersect all
(select course_id
from section
where semester = ’Spring’ and year= 2010);
The number of duplicate tuples that appear in the result is equal to
the minimum number of duplicates in both c1 and c2.
The Except Operation
To find all courses taught in the Fall 2009 semester but not in the
Spring 2010 semester, we write:
(select course_id
from section
where semester = ’Fall’ and year= 2009)
except
(select course_id
from section
where semester = ’Spring’ and year= 2010);
If we want to retain duplicates, we must write except all in place of
except:
(select course_id
from section
where semester = ’Fall’ and year= 2009)
except all
(select course_id
from section
where semester = ’Spring’ and year= 2010);
The number of duplicate copies of a tuple in the result is equal to
the number of duplicate copies in c1 minus the number of duplicate
copies in c2, provided that the difference is positive.