SQL (Set Operations)
DBMS
1
sql.php?d
G o
SET OPERATIONS
• UNION t1: aid A t2 : B aid
• INTERSECTION 1 a1 b1 1
• DIFFERENCE 2 a2 b3 3
3 a3 b5 5
• CARTESIAN (CROSS) Product
4 a4
t3: aid A
3 a3
4 a4
5 a5
6 a6
2
UNION
t1: aid A t3: aid A
SELECT * FROM t1
UNION 1 a1 3 a3
SELECT * FROM t3 2 a2 4 a4
3 a3 5 a5
4 a4 6 a6
Union operator eliminates duplicate tuples by
default, values of aid (3,4) are common or
duplicate in both table, so it appears one time
3
sql.php?d
G o
INTERSECTION
t1 : aid A t2: B aid t3 : aid A
1 a1 b1 1 3 a3
2 a2 4 a4
b3 3
5 a5
3 a3
b5 5
6 a6
4 a4
If we take intersection in the tables t1 & t3 If we take intersection in the tables t1 & t2
t1∩t3= aid A
t1∩t2= aid A B aid
3 a3 1 a1 b1 1
4 a4 3 a3 b3 3
4
INTERSECTION:
NTURAL JOIN can be used to implement the intersection between two tables t1 & t2
SELECT * FROM t1 NATURAL JOIN t2
5
INTERSECTION: INNER JOIN can also be used to implement the intersection between two
tables t1 & t2
SELECT * FROM t1 INNER JOIN t2 WHERE t1.aid=t2.aid
OR
SELECT * FROM t1 INNER JOIN t2 ON t1.aid=t2.aid
6
INTERSECTION: Retrieve data for some specific fields from both tables
SELECT t1.aid,t1.A,t2.B FROM t1 INNER JOIN t2 WHERE t1.aid=t2.aid
7
sql.php?d
G o
DIFFERENCE
t1 : aid A t2: B aid t3 : aid A
1 a1 3 a3
b1 1
2 a2 4 a4
b3 3
5 a5
3 a3
b5 5 6 a6
4 a4
If we take difference in the tables t1 & t3 If we take intersection in the tables t1 & t2
t1-t3= t1-t2= aid A B aid
aid A
1 a1 2 a2 NULL NULL
2 a2 4 a4 NULL NULL
8
DIFFERENCE: LEFT JOIN / LEFT OUTER JOIN can be used to implement the difference
between two tables t1 & t2 (i.e. t1-t2) as follows:
SELECT * FROM t1 LEFT JOIN t2 ON t1.aid=t2.aid WHERE t2.aid IS NULL
OR
SELECT * FROM t1 LEFT OUTER JOIN t2 ON t1.aid=t2.aid WHERE t2.aid IS NULL
9
DIFFERENCE: LEFT JOIN / LEFT OUTER JOIN can be used to implement the difference
between two tables t1 & t3 (i.e. t1-t3) as follows:
SELECT * FROM t1 LEFT JOIN t3 ON t1.aid=t3.aid WHERE t3.aid IS NULL
OR
SELECT * FROM t1 LEFT OUTER JOIN t3 ON t1.aid=t3.aid WHERE t3.aid IS NULL
10
Similarly RIGHT JOIN or RIGHT OUTER JOIN can be used to implement the difference
between two tables t2 & t1 (i.e. t2-t1) as follows:
SELECT * FROM t1 RIGHT JOIN t2 ON t1.aid=t2.aid WHERE t1.aid IS NULL
OR
SELECT * FROM t1 RIGHT OUTER JOIN t2 ON t1.aid=t2.aid WHERE t1.aid IS NULL
11
CROSS PRODUCT
t1: aid A
If we take cross product between Aid A B aid
1 a1 two tables t1 & t2 t1xt2=
1 a1 b1 1
2 a2
1 a1 b3 3
3 a3
1 a1 b5 5
4 a4
2 a2 b1 1
2 a2 b3 3
t2: B aid
2 a2 b5 5
b1 1 3 a3 b1 1
b3 3 3 a3 b3 3
3 a3 b5 5
b5 5
4 a4 b1 1
4 a4 b3 3
4 a4 b5 5
12
CROSS JOIN can be used to implement cross product between two tables t1 & t2 (i.e. t1xt2) as
follows:
SELECT * FROM t1 CROSS JOIN t2
13
References:
•North, Silbertz, Sudarshan, “Database Concepts”, Tata Mcgraw-hill Education
(India) Pvt. Ltd.
•Date C J, “An Introduction To Database System”, Addision Wesley
• Jain, Pillai, Singh “Introduction to Database Management”, BPB Publications.
14