SELECT Statement with ORDER BY clause

Written by Impact Atlas
Updated 9 months ago

The ORDER BY clause is used to sort the records in ascending or descending order.

ORDER BY Syntax

SELECT column_name(s)
FROM table_name
[ WHERE conditions ]
ORDER BY column_name(s)[ ASC|DESC ]

WHERE conditions: It is optional. It specifies conditions that must be fulfilled for the records to be selected. 

ASC: It is optional. It sorts the result set in ascending by column_name(s)

DESC: It is also optional. It sorts the result set in descending order by column_name(s)

If the ASC/DESC attributes are missing, the default sorting is ascending.

EXAMPLE 1:

Sort the participants by age in ascending order. We use the registration table to select the participant names and age.

In the example above, we omitted the ASC or DESC keyword in the ORDER BY clause so we can see that the participants have been sorted from youngest to oldest age. The query from the above screenshot is equivalent with the query from the below screenshot:

 

EXAMPLE 2:

Sort participants by first and last name in ascending order.

EXAMPLE 3:

Sort participants by first name in ascending order and last name in descending order.

EXAMPLE 4:

Select participants from two tables and sort them by name in ascending order.

Did this answer your question?