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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

This join-based syntax, for example, would have yielded exactly the same results (subject to possible sort<br />

differences). So why, then, would we need this new syntax? Performance — plain and simple.<br />

When you use the EXISTS keyword, <strong>SQL</strong> <strong>Server</strong> doesn’t have to perform a full row-by-row join. Instead, it<br />

can look through the records until it finds the first match and stop right there. As soon as there is a single<br />

match, the EXISTS is true, so there is no need to go further.<br />

Let’s take a brief look at things the other way around — that is, what if our query wanted the persons<br />

who were not employees? Under the join method that we looked at in Chapter 4, we would have had<br />

to make some significant changes in the way we went about getting our answers. First, we would have to<br />

use an outer join. Then we would perform a comparison to see whether any of the Employee records<br />

were NULL.<br />

It would look something like this:<br />

SELECT pp.BusinessEntityID, LastName + ', ' + FirstName AS Name<br />

FROM Person.Person pp<br />

LEFT JOIN HumanResources.Employee hre<br />

ON pp.BusinessEntityID = hre.BusinessEntityID<br />

WHERE hre.BusinessEntityID IS NULL;<br />

Which returns 19,682 rows:<br />

BusinessEntity ID Name<br />

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

293 Abel, Catherine<br />

295 Abercrombie, Kim<br />

2170 Abercrombie, Kim<br />

…<br />

…<br />

2088 Zugelder, Judy<br />

12079 Zukowski, Jake<br />

2089 Zwilling, Michael<br />

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

To do the same change over when we’re using EXISTS, we add only one word to the original EXIST<br />

query — NOT:<br />

SELECT BusinessEntityID, LastName + ', ' + FirstName AS Name<br />

FROM Person.Person pp<br />

WHERE NOT EXISTS<br />

(SELECT BusinessEntityID<br />

FROM HumanResources.Employee hre<br />

WHERE hre.BusinessEntityID = pp.BusinessEntityID);<br />

And we get back those exact same 19,682 rows.<br />

Chapter 7: Adding More to Our Queries<br />

The performance difference here is, in most cases, even more marked than with the inner join. <strong>SQL</strong><br />

<strong>Server</strong> just applies a little reverse logic versus the straight EXISTS statement. In the case of the NOT we’re<br />

now using, <strong>SQL</strong> can still stop looking as soon as it finds one matching record — the only difference is<br />

201

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

Saved successfully!

Ooh no, something went wrong!