- Order by (SQL)
An
ORDER BY
clause inSQL specifies that a SQLSELECT
statement returns aresult set with the rows being sorted by the values of one or more columns. The sort criteria do not have to be included in the result set. The sort criteria can be expressions, including - but not limited to - column names, user-defined functions, arithmetic operations, orCASE
expressions. The expressions are evaluated and the results are used for the sorting, i.e. the values stored in the column or the results of the function call.ORDER BY
is the "only" way to sort the rows in the result set. Without this clause, the relationaldatabase system may return the rows in any order. If an ordering is required, theORDER BY
must be provided in theSELECT
statement sent by the application. Although some database systems allow the specification of anORDER BY
clause in subselects or view definitions, the presence there has no effect. A view is a logical relational table, and the relational model mandates that a table is a set of rows, implying no sort order whatsoever. The only exception are constructs likeORDER BY ORDER OF ...
(not standardized in ) which allow the propagation of sort criteria through nested subselects.The SQL standard's core functionality does not explicitly define a default sort order for Nulls. With the extension T611, "Elementary OLAP operations", nulls can be sorted before or after all data values by using the
NULLS FIRST
orNULLS LAST
clauses of theORDER BY
list, respectively. Not all DBMS vendors implement this functionality, however. Vendors who do not implement this functionality may specify different treatments for Null sorting in the DBMS.cite journal | last = Coles, Michael | title = Null Versus Null? | journal = SQL Server Central | publisher = Red Gate Software |date=February 26 ,2007 | url = http://www.sqlservercentral.com/columnists/mcoles/2829.asp]Examples
References
Wikimedia Foundation. 2010.