In cases where data needs to be displayed in a sorted order, you can sort the query results based on the data in one or more columns.
The ORDER BY clause sorts a query's resulting record set on a specified field or fields in ascending or descending order.
SELECT * FROM tableName WHERE filterCondition
GROUP BY groupColumn HAVING filterCondition
ORDER BY orderItem [ASC | DESC]
Each orderItem must correspond to a column in the query results and can be one of the following:
- a field in a FROM table that is also a columnItem in the main SELECT clause
- a numeric expression indicating the location of the column in the result table. ( The leftmost column is number 1. )
ASC specifies an ascending order ( A to Z, 0 to 9 ) for query results, and is the default for ORDER BY, so can be omitted.
SELECT LastName, FirstName FROM Employees
ORDER BY LastName ASC
is the same as
SELECT LastName, FirstName FROM Employees
ORDER BY LastName
DESC specifies a descending order ( Z to A, 9 to 0 ) for query results. To sort in descending order, add the DESC keyword to the end of each field you want to sort in descending order.
SELECT LastName, Salary FROM Employees ORDER BY Salary DESC
You can include more than one field in the ORDER BY clause. Records are sorted first by the first field listed after ORDER BY. Records that have equal values in that field are then sorted by the value in the second field listed, and so on.
SELECT LastName, FirstName, Salary FROM Employees
ORDER BY Salary DESC, LastName, FirstName
Note that you cannot sort on Memo or OLE Object fields.
The sample at right shows how to pass a field argument to an ORDER BY clause to dynamically sort a Recordset.
ORDER BY is usually the last item in an SQL statement. In general, query results appear unordered if you don't specify an order with ORDER BY.