You are on page 1of 1

86 Chapter 3: Selecting

SELECT parent.parent_key,
parent.data_1,
child.child_key,
child.parent_key
FROM child LEFT OUTER JOIN parent ON parent.parent_key = child.parent_key
ORDER BY parent.parent_key,
child.child_key;

Tip: Outer joins are confusing at the best of times, so dont make the situation
worse by using both LEFT OUTER JOIN and RIGHT OUTER JOIN operators. Stick
with LEFT OUTER JOIN and your code will be easier to understand because the
preserved table will always be on the same side.

3.4.5 FULL OUTER JOIN


The FULL OUTER JOIN operator is an extension that combines both LEFT
OUTER JOIN and RIGHT OUTER JOIN functionality. In other words, all the
rows in both tables are preserved, and both tables are null-supplying when they
have to be. Heres how it works: First, the INNER JOIN is computed using the
ON condition. Second, any rows from the left-hand table that werent included
by the INNER JOIN process are now appended to the result set, with NULL
values used for the columns that would normally come from the right-hand
table. And finally, any rows from the right-hand table that werent included by
the INNER JOIN process are now appended to the result set, with NULL values
used for the columns that would normally come from the left-hand table.
Heres what the FULL OUTER JOIN looks like, using the parent and child
tables:
SELECT parent.parent_key,
parent.data_1,
child.child_key,
child.parent_key
FROM parent FULL OUTER JOIN child ON parent.parent_key = child.parent_key
ORDER BY parent.parent_key,
child.child_key;
Now the result set contains all the columns from all the rows in both tables. It
includes parent-and-child combinations from the INNER JOIN, plus the orphan
child row from the RIGHT OUTER JOIN, plus the childless parent rows from
the LEFT OUTER JOIN.
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
3 y NULL NULL -- parent with no children
Its important to understand that the ON condition only applies to the first step
in any OUTER JOIN process. All the rows in the preserved table(s) are included
in the final result set no matter what the ON condition says. Heres an example
where the restriction parent.data_1 = 'x' has been added to the ON condition of
the LEFT OUTER JOIN presented earlier:

You might also like