17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

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 4: JOINs<br />

100<br />

Somehow, we lost one of our vendors. That’s because <strong>SQL</strong> <strong>Server</strong> is applying the rules in the order that<br />

we’ve stated them. We have started with an OUTER JOIN between Vendors and VendorAddress. <strong>SQL</strong><br />

<strong>Server</strong> does just what we want for that part of the query — it returns all vendors. The issue comes when<br />

it applies the next set of instructions. We have a result set that includes all the vendors, but we now<br />

apply that result set as part of an INNER JOIN. Because an INNER JOIN is exclusive to both sides of the<br />

JOIN, only records where the result of the first JOIN has a match with the second JOIN will be included.<br />

Because only two records match up with a record in the Address table, only two records are returned in<br />

the final result set. We have two ways of addressing this:<br />

❑ Add yet another OUTER JOIN<br />

❑ Change the order of the JOINs<br />

Let’s try it both ways. We’ll add another OUTER JOIN first:<br />

SELECT v.VendorName, a.Address<br />

FROM Vendors v<br />

LEFT OUTER JOIN VendorAddress va<br />

ON v.VendorID = va.VendorID<br />

LEFT OUTER JOIN Address a<br />

ON va.AddressID = a.AddressID<br />

And now we get our expected result:<br />

VendorName Address<br />

--------------------------- ------------<br />

Don’s Database Design Shop 1234 Anywhere<br />

Dave’s Data 567 Main St.<br />

The <strong>SQL</strong> Sequel NULL<br />

(3 row(s) affected)<br />

Now do something slightly more dramatic and reorder our original query:<br />

SELECT v.VendorName, a.Address<br />

FROM VendorAddress va<br />

JOIN Address a<br />

ON va.AddressID = a.AddressID<br />

RIGHT OUTER JOIN Vendors v<br />

ON v.VendorID = va.VendorID<br />

And we still get our desired result:<br />

VendorName Address<br />

--------------------------- --------------<br />

Don’s Database Design Shop 1234 Anywhere<br />

Dave’s Data 567 Main St.<br />

The <strong>SQL</strong> Sequel NULL<br />

(3 row(s) affected)

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

Saved successfully!

Ooh no, something went wrong!