ORDER BY
When you use the SELECT
statement to query data from a table, the result set is not sorted. It means that the rows in the result set can be in any order.
To sort the result set, you add the ORDER BY
clause to the SELECT
statement. The following illustrates the syntax of the ORDER BY
clause:
In this syntax, you specify the one or more columns which you want to sort after the ORDER BY
clause.
The ASC
stands for ascending and the DESC
stands for descending. You use ASC
to sort the result set in ascending order and DESC
to sort the result set in descending order.
This ORDER BY
clause sorts the result set in ascending order:
And this ORDER BY
clause sorts the result set in descending order:
By default, the ORDER BY
clause uses ASC
if you don’t explicitly specify any option.
Therefore, the following clauses are equivalent:
and
If you want to sort the result set by multiple columns, you specify a comma-separated list of columns in the ORDER BY
clause:
It is possible to sort the result by a column in ascending order, and then by another column in descending order:
In this case, the ORDER BY
clause:
First, sort the result set by the values in the
column1
in ascending order.Then, sort the sorted result set by the values in the
column2
in descending order. Note that the order of values in thecolumn1
will not change in this step, only the order of values in thecolumn2
changes.
Note that the ORDER BY
clause is always evaluated after the FROM
and SELECT
clause.
Last updated