Specifications

The ORDER BY clause is used to sort the rows on one or more of the columns listed in the
SELECT clause. For example,
select name, address
from customers
order by name;
This query will return customer names and addresses in alphabetical order by name, like this:
+-----------------+--------------------+
| name | address |
+-----------------+--------------------+
| Alan Wong | 1/47 Haines Avenue |
| Julie Smith | 25 Oak Street |
| Melissa Jones | |
| Michael Archer | 12 Adderley Avenue |
| Michelle Arthur | 357 North Road |
+-----------------+--------------------+
(Notice that in this case, because the names are in firstname, lastname format, they are alpha-
betically sorted on the first name. If you wanted to sort on last names, youd need to have them
as two different fields.)
The default ordering is ascending (a to z or numerically upward). You can specify this if you
like using the ASC keyword:
select name, address
from customers
order by name asc;
You can also do it in the opposite order using the DESC (descending) keyword:
select name, address
from customers
order by name desc;
You can sort on more than one column. You can also use column aliases or even their position
numbers (for example, 3 is the third column in the table) instead of names.
Grouping and Aggregating Data
We often want to know how many rows fall into a particular set, or the average value of some
columnsay, the average dollar value per order. MySQL has a set of aggregate functions that
are useful for answering this type of query.
These aggregate functions can be applied to a table as a whole, or to groups of data within a
table.
Using MySQL
P
ART II
220
12 7842 CH09 3/6/01 3:36 PM Page 220