You are on page 1of 1

Chapter 3: Selecting 83

tables, and it is also called a Cartesian product. In the example above, one table
has two rows and the other one has three, so there are six rows in the result set:
c1 c2 c3
== == ==
1 1 7
1 1 8
1 1 9
2 1 7
2 1 8
2 1 9
The CROSS JOIN operator is the only one that doesnt allow unwanted rows to
be eliminated with the ON clause. Thats why its the simplest join operator, and
also why its the least useful: It usually returns too many rows. For example, a
CROSS JOIN of two ten-thousand-row tables would return one hundred million
rows.

3.4.2 INNER JOIN


The INNER JOIN operator together with an ON condition is far more useful
and far more common than CROSS JOIN. The INNER JOIN is often used to
join two tables using a foreign key relationship. Here is an example that joins
rows from a parent and child table using an ON condition to restrict the result
set; each child row is combined with only a single row in the parent table:
CREATE TABLE parent (
parent_key INTEGER NOT NULL,
data_1 VARCHAR ( 1 ) NOT NULL,
PRIMARY KEY ( parent_key ) );

CREATE TABLE child (


child_key INTEGER NOT NULL PRIMARY KEY,
parent_key INTEGER NULL REFERENCES parent ( parent_key ) );

INSERT parent VALUES ( 1, 'x' ); -- parent with three children


INSERT parent VALUES ( 2, 'x' ); -- parent with no children
INSERT parent VALUES ( 3, 'y' ); -- parent with no children

INSERT child VALUES ( 4, 1 ); -- child with parent


INSERT child VALUES ( 5, 1 ); -- child with parent
INSERT child VALUES ( 6, 1 ); -- child with parent
INSERT child VALUES ( 7, NULL ); -- orphan

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

You might also like