CNG351 Lecture 10 DML Part 2
CNG351 Lecture 10 DML Part 2
“SELECT - JOIN”
(SELECT * ...)
Query using EXISTS
Find all staff who work in a London branch.
SELECT staffNo, fName, lName, position
FROM Staff s
WHERE EXISTS
(SELECT *
FROM Branch b
WHERE s.branchNo = b.branchNo AND
city = ‘London’);
Query using EXISTS
• Note, search condition s.branchNo = b.branchNo is necessary to
consider correct branch record for each member of staff.
• If omitted, would get all staff records listed out because subquery:
SELECT * FROM Branch WHERE city=‘London’
• would always be true and query would be:
SELECT staffNo, fName, lName, position FROM Staff
WHERE true;
• Could also write this query using join construct:
SELECT staffNo, fName, lName, position
FROM Staff s, Branch b
WHERE s.branchNo = b.branchNo AND
city = ‘London’;
Union, Intersect, and Difference (Except)
• Can use normal set operations of Union, Intersection, and
Difference to combine results of two or more queries into a single
result table.
– Union of two tables, A and B, is table containing all rows in
either A or B or both.
– Intersection is table containing all rows common to both A and
B.
– Difference is table containing all rows in A but not in B.
• Two tables must be union compatible.
Union, Intersect, and Difference (Except)
• Format of set operator clause in each case is:
operator [ALL] [CORRESPONDING [BY {column1 [, ...]}]]
• If CORRESPONDING BY specified, set operation performed on the
named column(s).
• If CORRESPONDING specified but not BY clause, operation
performed on common columns.
• If ALL specified, result can include duplicate rows.
Union, Intersect, and Difference (Except)
Use of UNION
List all cities where there is either a branch office or a property.
(SELECT city
FROM Branch
WHERE city IS NOT NULL) UNION
(SELECT city
FROM PropertyForRent
WHERE city IS NOT NULL);
Use of INTERSECT
List all cities where there is both a branch office and a property.
SELECT b.city
FROM Branch b PropertyForRent p
WHERE b.city = p.city;
• Or:
SELECT DISTINCT city FROM Branch b
WHERE EXISTS
(SELECT * FROM PropertyForRent p
WHERE p.city = b.city);
Use of EXCEPT
List of all cities where there is a branch office but no properties.