O'Reilly logo

SQL in a Nutshell by Kevin Kline

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

ORDER BY Clause

Synopsis

The ORDER BY clause specifies the sort order of the result set retrieved by a SELECT statement.

Platform

Command

DB2

Supported, with limitations

MySQL

Supported, with limitations

Oracle

Supported, with variations

PostgreSQL

Supported, with variations

SQL Server

Supported, with limitations

SQL2003 Syntax

ORDER BY {sort_expression [COLLATE collation_name]
   [ASC | DESC]} [,...]

Keywords

ORDER BY

Specifies the order in which rows should be returned by a query. You should not anticipate a specific ordering if you exclude the ORDER BY clause, even if you specify a GROUP BY clause and it appears that a sort has been done.

sort_expression

Specifies an item in the query that will help determine the order of the result set. You can have multiple sort_expressions, and they are usually column names or column aliases from the query. However, they may also be expressions like (salary * 1.02). SQL92 allowed the use of ordinal positions for sort_expressions. This functionality has been deprecated, and should not be used in SQL2003 queries.

COLLATE collation_name

Overrides the default collation of the sort_expression, and applies the collation_name to the sort expression for the purposes of the ORDER BY clause.

[ASC | DESC]

Specifies that the sort_expression should be returned in either ascending order (ASC) or descending order (DESC).

Rules at a Glance

The ORDER BY clause should reference columns as they appear in the select item list of the SELECT statement, preferably ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required