20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7<br />

222<br />

Location.Street MemberDetails.Street<br />

NULL Main Road<br />

NULL 45 Upper Road<br />

NULL Newish Lane<br />

NULL Newish Lane<br />

NULL Long Lane<br />

NULL Main Street<br />

NULL Long Lane<br />

NULL Main Road<br />

NULL Newish Lane<br />

NULL Long Lane<br />

Winding Road Winding Road<br />

NULL White Cliff Street<br />

NULL NULL<br />

Because only one street name matches in the Location table, all the rows except one return NULL for<br />

Location.Street.<br />

Given that you could simply change the table names so that Location is on the right and MemberDetails<br />

is on the left, is there really any need or advantage to using a left outer join compared to a right outer<br />

join? Not really. Just use whatever makes sense to you at the time — whichever outer join is easiest to<br />

read. Performance differences often occur between inner and outer joins, but between left and right<br />

outer joins, it’s just a matter of personal preference.<br />

The discussion continues with another demonstration of a right outer join, except this time it also uses a<br />

second left outer join in the query as well. Imagine that the chairperson wants a list of all the film categories<br />

and the members who like films in each category. She wants all the categories listed, even if no<br />

member has selected the category as one of their favorites.<br />

Before starting, however, add a new category that no member has listed as his or her favorite, just to<br />

demonstrate that the query works and shows all categories even if no member has selected them as a<br />

favorite:<br />

INSERT INTO Category (CategoryId, Category) VALUES (9,’Film Noir’);<br />

The Category table contains a list of all the categories, so this is the table from which you want all the<br />

rows to be returned, regardless of whether there are matches in any other tables to which you might join<br />

it. Clearly, this is going to be the outer join table.<br />

The FavCategory table contains data on who likes which film categories, and each member’s details<br />

come from the MemberDetails table. You need to outer-join Category and FavCategory together to get

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!