Sie sind auf Seite 1von 1

# Chapter 3: Selecting 89

Section 3.4.5, FULL OUTER JOIN, because the WHERE clause hasnt been
applied yet:
parent. parent. child. child.
parent_key data_1 child_key parent_key
========== ======= ========= ==========
NULL NULL 7 NULL -- this row is going to disappear: not OK
1 x 4 1
1 x 5 1
1 x 6 1
2 x NULL NULL
3 y NULL NULL -- this row is going to disappear: OK
When the WHERE clause is applied to produce the final result set, two rows are
eliminated, not just one. The first row above is eliminated because parent.data_1
is NULL and the last row is eliminated because parent.data_1 is 'y'; neither
match the WHERE condition parent.data_1 = 'x'.
In other words, the FULL OUTER JOIN isnt a FULL OUTER JOIN any-
more because the orphan child row is no longer represented in the final result
set; adding the WHERE clause effectively turned it into a LEFT OUTER JOIN.
parent. parent. child. child.
parent_key data_1 child_key parent_key
========== ======= ========= ==========
1 x 4 1
1 x 5 1
1 x 6 1
2 x NULL NULL
In fact, if there were a thousand orphan rows in the child table, they would all
be eliminated by that WHERE clause, when all we wanted to do is eliminate
one parent row, the one with parent.data_1 different from 'x'.
The solution once again is a derived table that eliminates the unwanted par-
ent row before the FULL OUTER JOIN is computed:
SELECT parent.parent_key,
parent.data_1,
child.child_key,
child.parent_key
FROM ( SELECT *
FROM parent
WHERE parent.data_1 = 'x' ) AS parent
FULL OUTER JOIN child ON parent.parent_key = child.parent_key
ORDER BY parent.parent_key,
child.child_key;
Now the result set makes more sense the orphan child row is included, and
the unwanted parent row is eliminated:
parent. parent. child. child.
parent_key data_1 child_key parent_key
========== ======= ========= ==========
NULL NULL 7 NULL -- orphan
1 x 4 1 -- parent and child
1 x 5 1 -- parent and child
1 x 6 1 -- parent and child
2 x NULL NULL -- parent with no children