Set operations combines the results of two independent SQL queries. There are three set operations in SQL
These set operations operate on relations and are based on the general principles of mathematical set theory that you’ve probably covered in school level math.
One thing to not forgot is, each of these operations automatically eliminates duplicates in the result. In order to retain all the duplicates, one can use the corresponding multiset versions of basic set operations union all, intersect all and except all.
Suppose a tuple/row occurs m times in a relation named r and n times in relation named s then it occurs
m + n times in
r union all s
min(m,n) times in
max(0, m – n) times in
r except all s.
Some example queries are shown in image below:
The relation schemes for all the examples used above are:
Branch(bname, bcity, assets)
Customer(cname, street, ccity)
Account(bname, account#, balance)
Loan(bname, loan#, amount)