Sorting query results: ORDER BY

Previous Index Next

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:
class_num stud_id name
4 91131 Hung Wai Ming
7 91194 Sung Hing Wah, Patrick
1 92114 Chan Wai Man, Raymond
2 92133 Chow Chi Ling
9 92145 Wong Ka Tak, Kent
5 92153 Leung King
6 92211 Poon Kwok Fai
10 93211 Yeung Chun
3 94302 Fung Ching Man, Mandy
12 94412 Chan Lai Yin
14 95343 Chung Kwok Fai, Fred
11 96374 Lai Fung Chun
15 97233 Lee Lai May
8 97602 Tang Wing Chi
13 98832 Man Fook Wing
 
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:
name clc ue
Man Fook Wing 55 77
Poon Kwok Fai 59 60
Chan Wai Man, Raymond 64 55
Lee Lai May 67 71
Yeung Chun 69 80
Sung Hing Wah, Patrick 70 72
Chow Chi Ling 70 62
Chung Kwok Fai, Fred 72 62
Fung Ching Man, Mandy 72 50
Lai Fung Chun 78 75
Tang Wing Chi 80 79

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.

Previous Index Next