Monday, September 10, 2007

Full Outer Join:

Consider that we need to join two physical files using SQL. It's possible that some records in the first file won't have matches in the second file. It's also possible that some records in the second file won't have matches in the first file. If we require getting all the records in both file then the question of ‘What type of join to use’ arises.

The formula that we can use for it is,
Left outer join + Right Exception join = Full Outer join.

Consider the following example.
Consider that we have Faculty Master Table and Schedule table. We need a list of the professors and the classes each one has been assigned to teach. Some professors have not yet been assigned to teach any classes. Some classes have not yet been assigned to a professor. We would require a full Schedule list.

Faculty Table
Professor ID Name
P01 Cake, Patty
P02 Dover, Ben
P03 Flett, Pam

Schedule:
Class ID Period Building Room Instructor
101 A 41 320 P02
102 A 41 218 P03
103 B 41 212 P02
104 B 42 302 NULL
105 C 41 165 P04
Notice a few things:
• No classes have been assigned to instructor P01.
• Class 104 has not been assigned to an instructor.
• Class 105 has been assigned to non-existent instructor P04.
Here's the join:

SELECT f.FacID, f.Name, s.classID, s.period, s.Building, s.Room
FROM Faculty AS f
LEFT JOIN Schedule AS s
ON f.FacID = s.Instructor
UNION
SELECT s.Instructor, f.Name, s.classID, s.period, s.Building, s.Room
FROM Faculty AS f
RIGHT EXCEPTION JOIN Schedule AS s
ON f.FacID = s.Instructor

Here is the result set.

Instructor ID Instructor Class Period Building Room
P01 Cake, Patty NULL NULL NULL NULL
P02 Dover, Ben 101 A 41 320
P02 Dover, Ben 103 B 41 212
P03 Flett, Pam 102 A 41 218
NULL NULL 104 B 42 302
P04 NULL 105 C 41 165

No comments: