ORDER BY Clause
The ORDER BY clause sorts query results by specified columns or expressions.
Element | Description | Restrictions | Syntax |
---|---|---|---|
column | Sort rows by value in this column | None | Identifier |
display_label | Temporary name for a column or for a column expression | Must be unique among labels declared in the Projection clause | Identifier |
first, last | First and last byte in column substring to sort the result set | Integers; for BYTE, TEXT, and character data types only | Literal Number |
select_ number | Ordinal position of a column in the select list of the Projection clause | See GROUP BY Clause. | Literal Number |
table | Name, synonym, or alias of the table or view containing column | Must exist and must be specified in the FROM clause | Identifier |
The ORDER BY clause implies that the query returns more than one row. In SPL, the database server issues an error if you specify the ORDER BY clause without a FOREACH loop to process the returned rows individually within the SPL routine.
SELECT vcol FROM
(SELECT FIRST 5 col1 FROM tab1 ORDER BY col1) vtab(vcol);
ORDER BY in NLSCASE INSENSITIVE databases
In databases created with the NLSCASE INSENSITIVE property, operations on columns and expressions of NCHAR or NVARCHAR data types make no distinction between upper case and lower case letters. For this reason, queries that include the ORDER BY clause might return rows in a sequence that disregard variants in letter case, if the column or expression are of NLS data types, and the data includes values that differ only in letter case.
If the data set includes letter case variants of the same string, these will be processed as duplicates, with case variants listed in their order of retrieval. For example, a set of NCHAR or NVARCHAR strings that were processed as duplicates might appear in this order:
gAMma GAmma GaMMa gamma GAMMA
For more information, see Duplicate rows in NLSCASE INSENSITIVE databases and NCHAR and NVARCHAR expressions in case-insensitive databases.