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:

SELECT 
   select_list
FROM 
   table_name
ORDER BY 
   column1 [ASC|DESC], 
   column2 [ASC|DESC],
   ...;

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:

ORDER BY column1 ASC;

And this ORDER BY clause sorts the result set in descending order:

ORDER BY column1 DESC;

By default, the ORDER BY clause uses ASC if you don’t explicitly specify any option.

Therefore, the following clauses are equivalent:

ORDER BY column1 ASC;

and

ORDER BY column1;

If you want to sort the result set by multiple columns, you specify a comma-separated list of columns in the ORDER BY clause:

ORDER BY
   column1,
   column2;

It is possible to sort the result by a column in ascending order, and then by another column in descending order:

ORDER BY
    column1 ASC,
    column2 DESC;

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 the column1 will not change in this step, only the order of values in the column2 changes.

Note that the ORDER BY clause is always evaluated after the FROM and SELECT clause.

Last updated