As seen from the previous examples, the query results are in the order of the record number in the original table. We would like to see the results to be displayed in an order we prefer.
The syntax for a SELECT statement using the ORDER BY clause is as follows:
SELECT <list_of_fields> FROM <table_name> [<WHERE_clause>]
ORDER BY <expression> [ASC | DESC] {, <expression> [ASC
| DESC]}
In the ORDER BY clause, an <expression> can be any field name or alias that appears in <list_of_fields>.
The keyword ASC indicates that the results are to be sorted in ascending order of the expression specified. On the other hand, the keyword DESC indicates that the results are to be sorted in descending order of the expression specified. If ASC or DESC are not specified in the ORDER BY clause, the sorting order is understood to be ascending.
If more than one expressions are specified in the ORDER BY clause, the first one will be the primary key of sorting, the second one will be the secondary key and so on.
The following are some examples:
List the class numbers, student IDs and the names of the students in ascending order of the student IDs. | ||||||||||||||||||||||||||||||||||||||||||||||||
SELECT class_num, stud_id, name FROM s6a ORDER BY stud_id | ||||||||||||||||||||||||||||||||||||||||||||||||
Output:
|
List the names and the marks of CLC and UE of those students who pass in both subjects (pass mark is 50). The results should be displayed in ascending order of the CLC mark. If there exist more than one records having the same CLC mark, they should be displayed in descending order of the UE mark. | ||||||||||||||||||||||||||||||||||||
SELECT name, clc, ue FROM
s6a WHERE clc >= 50 AND ue >= 50 ORDER BY clc ASC, ue DESC |
||||||||||||||||||||||||||||||||||||
Output:
Note that both Sung Hing Wah, Patrick and Chow Chi Ling get 70 marks in CLC, but Sung Hing Wah, Patrick has a higher mark in UE. Therefore his record appears before Chow Chi Ling's. Similarly, Chung Kwok Fai, Fred's record appears before Fung Ching Man, Mandy's. |