You are on page 1of 1

88 Chapter 3: Selecting

LEFT OUTER JOIN child ON parent.parent_key = child.parent_key


ORDER BY parent.parent_key,
child.child_key;

Tip: The minimum coding requirements for a derived table are a subquery
inside brackets, followed by a correlation name by which the subquerys result
set will be known in the rest of the FROM clause. If all you want from a derived
table is to apply a WHERE clause to a table, theres no reason not to use SELECT
* in the subquery. You can also use the table name as the correlation name if
you want, and you dont have to specify alias names for any of the columns; in
other words, the derived table can look exactly like the original table, as far as
the table and column names are concerned. Also, you dont necessarily have to
worry about performance; the query optimizer does a pretty good job of turning
subqueries into joins and eliminating columns that arent actually needed.

In the LEFT OUTER JOIN example above, the derived table is called parent
and it looks like this:
( SELECT *
FROM parent
WHERE parent.data_1 = 'x' ) AS parent
Now only rows with parent.data_1 = 'x' are considered for the LEFT OUTER
JOIN with the child table, and the final result set looks like this:
parent. parent. child. child.
parent_key data_1 child_key parent_key
========== ======= ========= ==========
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
It is sometimes tempting to use a WHERE clause in the outer SELECT, instead
of an ON condition inside a FROM clause, especially if the ON condition
doesnt work and you dont want to bother with a derived table. With an
OUTER JOIN, however, a WHERE clause is like an ON condition some-
times it does what you want, and sometimes it doesnt. In particular, a WHERE
clause is applied long after the FROM clause is completely evaluated, and it can
accidentally eliminate rows where columns were filled with NULL values from
the null-supplying table.
Here is an example using the FULL OUTER JOIN from earlier; an attempt
is being made to restrict the parent rows to ones where parent.data_1 = 'x' by
adding that restriction in a WHERE clause:
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
WHERE parent.data_1 = 'x'
ORDER BY parent.parent_key,
child.child_key;
According to the explanation in Section 3.2, Logical Execution of a SELECT,
the FROM clause is evaluated first and the WHERE clause is applied later. That
means the initial result of the FROM clause looks exactly as it did earlier, in

You might also like