Sorting in SQL Server

Using the ORDER BY Clause

SELECT 
 name AS FirstName,
 residence AS [Home City],
 age 
FROM
 person
ORDER BY FirstName

The ORDER BY clause allows you to sort your query results by the column that is specified after it.  ORDER BY FirstName ASC as used in the query above would sort the query result by the alias column FirstName in ascending order.  The default sort order is ascending, i.e A-Z.  The keyword ASC  which specifies Ascending order, is optional.  To sort in descending order, i.e Z-A we would add the keyword DESC after the column being sorted.  ORDER BY FirstName DESC would sort the aliased column FirstName in descending order. 

You can sort multiple columns as well.  ORDER BY age DESC, FirstName ASC would first sort the age column in descending order, then sort the FirstName column in ascending order.

3.) Write a query that return the account number and name from the account table.

4.) Create an alias for the account and name columns of the account table then sort the account table by name then account number.

5.) Write a query that return the account number and name from the account table.  Sort this query by city only.

 

Selecting the Top 10 Records

Adding the keywords Top 10 returns only the first 10 records from your query in the sort order you specify.

SELECT Top 10  
 name AS FirstName, 
 residence AS [Home City], 
 age  
FROM person 
ORDER BY FirstName

 

SELECT   
 name AS FirstName, 
 residence AS [Home City], 
 age  
FROM person 
ORDER BY FirstName
LIMIT 10

The query above would return the first ten records from the person table sorted by FirstName.  You can replace 10 with any number and it will return the number of records you specify (provided that there are at least that many records in the table)

6.) Write a query that returns the top 7 account numbers, sorted by city.

7.) Write a query that returns the last seven names from the account table.  Alaus the names column as "First Name"