1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
Order By
========
The ORDER BY keyword is used to sort the result-set by column; by default, it sorts the records in ascending order.
SQL ORDER BY Syntax: ::
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC;
**ORDER BY Example**
The "Persons" table:
+---------+------------+----------+----------+--------+
|Id |LastName |FirstName |Address | City |
+=========+============+==========+==========+========+
| 1 | Larson | Sue |3 Cherry | Chicago|
+---------+------------+----------+----------+--------+
| 2 | Roberts | Teri |21 Brown | Chicago|
+---------+------------+----------+----------+--------+
| 3 | Peterson | Kari |30 Mell | Reno |
+---------+------------+----------+----------+--------+
To select all the persons from the table above, and also sort them by their last name, use the following SELECT statement: ::
SELECT * FROM Persons
ORDER BY LastName;
The result-set will look like this:
+---------+------------+----------+----------+--------+
|Id |LastName |FirstName |Address | City |
+=========+============+==========+==========+========+
| 1 | Larson | Sue |3 Cherry | Chicago|
+---------+------------+----------+----------+--------+
| 3 | Peterson | Kari |30 Mell | Reno |
+---------+------------+----------+----------+--------+
| 2 | Roberts | Teri |21 Brown | Chicago|
+---------+------------+----------+----------+--------+
ORDER BY DESC can be used to reverse the order of the result set. ::
SELECT * FROM Persons
ORDER BY LastName DESC;
|