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 3: The Foundation Statements of T-<strong>SQL</strong><br />

52<br />

This will produce the following results:<br />

Name ProductNumber ReorderPoint<br />

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

Adjustable Race AR-5381 750<br />

Bearing Ball BA-8327 750<br />

...<br />

...<br />

Road-750 Black, 48 BK-R19B-48 75<br />

Road-750 Black, 52 BK-R19B-52 75<br />

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

As it happened, our query result set was sorted in ProductID order. Why? Because <strong>SQL</strong> <strong>Server</strong> decided<br />

that the best way to look at this data was by using an index that sorts the data by ProductID. That just<br />

happened to be what created the lowest-cost (in terms of CPU and I/O) query. Were we to run this exact<br />

query when the table has grown to a much larger size, <strong>SQL</strong> <strong>Server</strong> might have choose an entirely different<br />

execution plan, and therefore might sort the data differently. We could force this sort order by changing<br />

our query to this:<br />

SELECT Name, ProductNumber, ReorderPoint<br />

FROM Production.Product<br />

ORDER BY Name;<br />

Note that the WHERE clause isn’t required. It can either be there or not depending on what you’re trying<br />

to accomplish. Just remember that if you do have a WHERE clause, it goes before the ORDER BY clause.<br />

Unfortunately, that previous query doesn’t really give us anything different, so we don’t see what’s<br />

actually happening. Let’s change the query to sort the data differently — by the ProductNumber:<br />

SELECT Name, ProductNumber, ReorderPoint<br />

FROM Production.Product<br />

ORDER BY ProductNumber;<br />

Now our results are quite different. It’s the same data, but it’s been substantially rearranged:<br />

Name ProductNumber ReorderPoint<br />

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

Adjustable Race AR-5381 750<br />

Bearing Ball BA-8327 750<br />

LL Bottom Bracket BB-7421 375<br />

ML Bottom Bracket BB-8107 375<br />

...<br />

...<br />

Classic Vest, L VE-C304-L 3<br />

Classic Vest, M VE-C304-M 3<br />

Classic Vest, S VE-C304-S 3<br />

Water Bottle - 30 oz. WB-H098 3<br />

(504 row(s) affected)

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

Saved successfully!

Ooh no, something went wrong!