Database Reference
In-Depth Information
The default sort direction is ascending. To make the direction for an ascending sort
explicit, add ASC after the sorted column's name:
SELECT * FROM driver_log ORDER BY name ASC ;
The opposite (or reverse) of ascending order is descending order, specified by adding
DESC after the sorted column's name:
mysql> SELECT * FROM driver_log ORDER BY name DESC;
+--------+-------+------------+-------+
| rec_id | name | trav_date | miles |
+--------+-------+------------+-------+
| 2 | Suzi | 2014-07-29 | 391 |
| 7 | Suzi | 2014-08-02 | 502 |
| 10 | Henry | 2014-07-30 | 203 |
| 8 | Henry | 2014-08-01 | 197 |
| 6 | Henry | 2014-07-26 | 115 |
| 4 | Henry | 2014-07-27 | 96 |
| 3 | Henry | 2014-07-29 | 300 |
| 5 | Ben | 2014-07-29 | 131 |
| 9 | Ben | 2014-08-02 | 79 |
| 1 | Ben | 2014-07-30 | 152 |
+--------+-------+------------+-------+
Closely examine the output from the queries just shown and you'll notice that although
rows are sorted by name, rows for any given name are in no special order. (The
trav_date values aren't in date order for Henry or Ben, for example.) That's because
MySQL doesn't sort something unless you tell it to:
• The overall order of rows returned by a query is indeterminate unless you specify
an ORDER BY clause.
Within a group of rows that sort together based on the values in a given column,
the order of values in other columns also is indeterminate unless you name them
in the ORDER BY clause.
To more fully control output order, specify a multiple-column sort by listing each col‐
umn to use for sorting, separated by commas. The following query sorts in ascending
order by name and by trav_date within the rows for each name:
mysql> SELECT * FROM driver_log ORDER BY name, trav_date;
+--------+-------+------------+-------+
| rec_id | name | trav_date | miles |
+--------+-------+------------+-------+
| 5 | Ben | 2014-07-29 | 131 |
| 1 | Ben | 2014-07-30 | 152 |
| 9 | Ben | 2014-08-02 | 79 |
| 6 | Henry | 2014-07-26 | 115 |
| 4 | Henry | 2014-07-27 | 96 |
| 3 | Henry | 2014-07-29 | 300 |
| 10 | Henry | 2014-07-30 | 203 |
Search WWH ::




Custom Search