The ORDER BY clause

 

The ORDER BY clause is used to sort and order the rows of data in a result data set by the values contained in the column(s) specified. In the ORDER BY clause, you specify the column or columns to be used as the ordering key. You then specify whether records are to appear in ascending or descending order of magnitude. The following example returns all the records in the Employees table, listed by department ID and last name in alphabetical order:

 

SELECT LastName, FirstName, DeptID
FROM Employees
ORDER BY DeptID ASC, LastName ASC

 

In this example, the ASC (for "ascending order") is optional. The default sort order is ascending (A – Z, 0 – 9). However, you may want to include the ASC keyword at the end of each field you want to sort in ascending order. This will clearly document the ORDER BY clause.

 

Both of the following examples sort employee names in last name order:

 

SELECT LastName
FROM Employees
ORDER BY LastName ASC

or

SELECT LastName
FROM Employees
ORDER BY LastName

 

To sort in descending order (Z – A, 9 – 0), add the DESC keyword to the end of each field you want to sort in descending order.

 

ORDER BY is usually the last item in an SQL statement. It is optional (unless you use the TOP or TOP n PERCENT predicate in the SELECT clause). If you don't include ORDER BY, the data is displayed unsorted.