Microsoft SQL Server ResourcesSorting Records in a SQL Server View

Provided by: Michelle Swann-Renee, EVP Professional Solutions Group

Overview

Many times developers need to order items in a view rather than using a stored procedure. However, adding an order by clause to a view generates an error.

To get around this, use the TOP key word to select the items and add the Order By clause.

Example

To select a list of employees and order the results from oldest to youngest, you would use the following SQL:

Select TOP 100 Percent LastName, FirstName, Title, BirthDate From Employees Order By BirthDate

To retrieve a specific number of rows avoid the PERCENT:

Select TOP 25 LastName, FirstName, Title, BirthDate From Employees Order By BirthDate

 

Return to the tips page