Sorting Data (ORDER BY)

The order by keywords enable you to define the sort order for a result set. Notice that ORDER BY affects the result set, not the original table. This is crucial. To affect the sorting of a table, you need to modify its indexes (see Day 9, "Indexes and Performance," ), but you can change the order of the data you are reviewing.

It's important to do as much of the sorting as possible in SQL Server instead of sorting data locally in a client application. The server has resources to improve sort performance and to handle very large sorts. Take advantage of these resources and your overall performance will improve.

Sorting by One Column

To sort data, add an ORDER BY clause to your SELECT statement after the WHERE clause, as in ...

Get Sams Teach Yourself Transact-SQL in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.