ORDER BY
When a SELECT
statement is executed, the result set is not sorted in any way.It often happens that rows appear to be sorted chronologically, simply because they are returned in the same order they were added to the table by INSERT
statements.This is not something you should rely on: the order may change depending on the plan or updates to rows, etc.To specify an explicit sorting order for the set specification, an ORDER BY
clause is used.
SELECT ... FROM ... ... ORDER BY <sort-specification [, <sort-specification> ...] <sort-specification> ::= <value-expression> [<ordering-specification>] [<null-ordering>] <ordering-specification> ::= ASC | ASCENDING | DESC | DESCENDING <null-ordering> ::= NULLS FIRST | NULLS LAST
Argument | Description |
---|---|
value-expression |
Any expression;an expression that is only an integer literal represents the column position |
The ORDER BY
consists of a comma-separated list of the columns or expressions on which the result data set should be sorted.The sort order can be specified by the name of the column — but only if the column was not previously aliased in the SELECT
columns list.The alias must be used if it was used in the select list.The ordinal position number of the column in the SELECT
column list, the alias given to the column in the SELECT
list with the help of the AS
keyword, or the number of the column in the SELECT
list can be used without restriction.
The three forms of expressing the columns for the sort order can be mixed in the same ORDER BY
clause.For instance, one column in the list can be specified by its name and another column can be specified by its number.
Important
|
If you sort by column position or alias, then the expression corresponding to this position (alias) will be copied from the |
Note
|
If you use the column position to specify the sort order for a query of the |