4
The ORDER BY keyword is used to sort the result-set by column; by default, it sorts the records in ascending order.
12
ORDER BY column_name(s) ASC|DESC;
18
+---------+------------+----------+----------+--------+
19
|Id |LastName |FirstName |Address | City |
20
+=========+============+==========+==========+========+
21
| 1 | Larson | Sue |3 Cherry | Chicago|
22
+---------+------------+----------+----------+--------+
23
| 2 | Roberts | Teri |21 Brown | Chicago|
24
+---------+------------+----------+----------+--------+
25
| 3 | Peterson | Kari |30 Mell | Reno |
26
+---------+------------+----------+----------+--------+
28
To select all the persons from the table above, and also sort them by their last name, use the following SELECT statement:
35
The result-set will look like this:
37
+---------+------------+----------+----------+--------+
38
|Id |LastName |FirstName |Address | City |
39
+=========+============+==========+==========+========+
40
| 1 | Larson | Sue |3 Cherry | Chicago|
41
+---------+------------+----------+----------+--------+
42
| 3 | Peterson | Kari |30 Mell | Reno |
43
+---------+------------+----------+----------+--------+
44
| 2 | Roberts | Teri |21 Brown | Chicago|
45
+---------+------------+----------+----------+--------+
47
ORDER BY DESC can be used to reverse the order of the result set.
52
ORDER BY LastName DESC;
56
add something about SELECT * without ORDER BY being non-deterministic
60
add something about how ORDER BY is executed. index scan vs filesort