Overview
TheORDER 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 theORDER BY
clause:
Parameters
columns
: columns that you wish to retrievetable_name
: table that you want to retrieve records from.ORDER BY
: expression used to order the resultsASC
orDESC
: optional parameter to specify the order in which the results should be returned, either ascending or descending. Default is set toASC
Examples
We will use the table called salaryemp as an example. In order to create the table, please run the query below:Using ORDER BY
in ascending order
This example uses the ORDER BY
clause to sort employees by their division:
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:
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:
Using ORDER BY
with TEXT
data types
In this example we are going to create to small tables with above mentioned data types:
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.
hours
and days
.