Skip to main content

Overview

The ORDER BY clause is used to sort rows of the result received from a SELECT statement, which retrieves records from one or more tables.

Syntax

The following illustrates the syntax of the ORDER BY clause:

Parameters

  • columns: columns that you wish to retrieve
  • table_name: table that you want to retrieve records from.
  • ORDER BY: expression used to order the results
  • ASC or DESC: optional parameter to specify the order in which the results should be returned, either ascending or descending. Default is set to ASC

Examples

We will use the table called salaryemp as an example. In order to create the table, please run the query below:
To verify that the values have been inserted successfully, retrieve the results by executing the following code:

Using ORDER BY in ascending order

This example uses the ORDER BY clause to sort employees by their division:
The above query will provide you with the following output:

Using ORDER BY in descending order

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:

Using ORDER BY with both ASC & DESC parameters

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 following output:

Using ORDER BY with TEXT data types

In this example we are going to create to small tables with above mentioned data types:
When using the ORDER BY clause with these types of data, records with uppercase letters will be sorted lexicographically first, followed by records with lowercase letters.

Using ORDER BY with INTERVAL data type

For this example, we’ll create a new table called interval_data:
ORDER BY on INTERVAL column will sort the values by their leading most significant time unit. In this case months. First are all 1 month values, then all 2 months values.
It works the same for other time units, such as hours and days.