Order By Clause
The ORDER BY clause specifies the columns on which the results table is to be sorted. Columns in the ORDER BY clause can be specified using either the column name or a number corresponding to the position of the column in the FROM clause. (You must specify unnamed result columns using a number.) In a union select, use numbers to specify the columns in the ORDER BY clause; column names cannot be used.
For example, if the employees table contains the following data:
then this query:
select emanager, ename, edept from employees
order by emanager, edept, ename
produces this list of managers, the departments they manage, and the employees in each department:
and this query:
select ename, edept, emanager from employees
order by ename
produces this alphabetized employee list:
To display result columns sorted in descending order (numeric or alphabetic), specify ORDER BY columnname desc. For example, to display the employees in each department from oldest to youngest:
select edept, ename, eage from employees
order by edept, eage desc;
If a nullable column is specified in the order by clause, nulls are sorted to the beginning or end of the results table, depending on the host DBMS.
Note: If the ORDER BY clause is omitted, the order of the rows in the results table is not guaranteed by the DBMS. In particular, the order of the rows in the results table is not guaranteed to have any relationship to the source tables' storage structure or key structure.