ORDER BY

ORDER BY is an optional clause that enables you to sort the result of a query. The records can be sorted alphabetically or numerically, depending on the data type of the value that is used as the basis for the sorting operation. The syntax of the ORDER BY clause is as follows:

SELECT [ column(s) ]
FROM [ tables ]
ORDER BY [ column(s) ] [ASC | DESC] ;

ORDER BY can be used in combination with ASC or DESC. Using DESC will have the effect that the record are sorted in a descending order. By default, the records are sorted in an ascending order.

The following query will return all the rows from the table CREATOR, sorted in a descending order.

SELECT *
FROM CREATOR
ORDER BY NAME_LAST DESC;

It is also possible to sort the data by more than one column. To do this, you need to mention these columns after ORDER BY and separate them by commas. The next example firstly sorts all the rows by subject. Secondly, those items which have the same subject are sorted chronologically.


SELECT *
FROM TREASURE
ORDER BY SUBJECT, YEAR ;

Exercises

  1. Select the last name, the first name and the year of birth of all the persons in the table CREATOR. Sort the rows by year of birth. The most recent year should appear first
  2. Select all the rows in the table CITY, and sort the rows alphabetically.
  3. Select the distinct subject codes in the table TREASURE, and sort the result alphabetically.