The ORDER BY clause is used to sort the rows of the result set from a SELECT statement.
The SELECT statement is used to retrieve records from one or more tables.
The following illustrates the syntax of the ORDER BY clause:
The parameters and arguments from the syntax are explained below:
- columns: The columns that you wish to retrieve.
- table_name: The tables that you want to retrieve records from.
- ORDER BY: It is an expression used to order the results as you wish to return. The expression could be ascending (ASC) or descending (DESC).
We will use the table called salaryemp for an example. Run the query below to create the table:
To verify that the values have been inserted successfully, retrieve the result set using the command below:
This example uses the ORDER BY clause to sort employees by their division:
The ASC option is the default expression of ORDER BY, you can omit it in the query.
The above query will give the following result:
The following statement selects the employee name and employee salary from the salaryemp table and sorts the records in the emp_sal column in descending order:
The result of the query is as follows:
The following statement selects all records from the salaryemp table and sorts the rows by employee salary in ascending order and employee division in descending order:
After implementing the above command, we will get the below output: