Export (0) Print
Expand All
Expand Minimize

ORDER BY Clause (SQL Server Compact)

Specifies the sort order for the result set. The ORDER BY clause is not valid in subqueries.


[ ORDER BY { order_by_expression [ ASC | DESC ] } [ ,...n] ] 

order_by_expression

Specifies a column on which to sort. A sort column can be specified as a name or column alias, which can be qualified by the table name, or an expression. Multiple sort columns can be specified. The sequence of the sort columns in the ORDER BY clause defines the organization of the sorted result set.

The ORDER BY clause can include items not appearing in the select list.

ms173288.note(en-us,SQL.100).gifNote:
Columns of data type ntext and image cannot be used in an ORDER BY clause.

ASC

Specifies that the values in the specified column should be sorted in ascending order, from lowest value to highest value.

DESC

Specifies that the values in the specified column should be sorted in descending order, from highest value to lowest value. Null values are treated as the lowest possible values.

There is no limit to the number of items in the ORDER BY clause.

If the ORDER BY clause is used with a UNION statement, then the columns on which you sort must be the column names or aliases specified in the first SELECT statement. For example, the first of the following SELECT statement succeeds, while the second fails:

Create t1 (col1 int, col2 int);

Create t2 (col3 int, col4 int);

SELECT * from t1 UNION SELECT * from t2 ORDER BY col1;

This statement succeeds because col1 belongs to the first table (t1)

SELECT * from t1 UNION SELECT * from t2 ORDER BY col3;

This statement fails because col3 does not belong to the first table (t1)

The following example lists employees by their first names.

SELECT FirstName + ' ' + LastName FROM Employees ORDER BY FirstName
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft