6.7.3. Grouping and Ordering
The results you get back from a select are, by default, indeterminate
in the order they will appear. Fortunately, SQL provides some tools
for imposing order on this seemingly random list. The first
tool -- available in both MySQL and mSQL -- is ordering. You
can tell a database that it should order any results you see by a
certain column. For example, if you specify that a query should order
the results by last_name, then the results will
appear alphabetized according to the last_name
value. Ordering comes in the form of the ORDER BY
clause:
SELECT last_name, first_name, age
FROM people
ORDER BY last_name, first_name
In this situation, we are ordering by two columns. You can order by
any number of columns, but the columns must be named in the
SELECT clause. If we had failed to select the
last_name above, we could not have ordered by the
last_name field.
Grouping is an ANSI SQL tool that MySQL implements but mSQL does not.
Because mSQL does not have any concept of aggregate functions,
grouping simply does not make sense in mSQL. As its name implies,
grouping lets you group rows with a similar value into a single row
in order to operate on them together. You usually do this to perform
aggregate functions on the results. We will go into functions a
little later in the chapter.
Consider the following:
mysql> SELECT name, rank, salary FROM people\g
+--------------+----------+--------+
| name | rank | salary |
+--------------+----------+--------+
| Jack Smith | Private | 23000 |
| Jane Walker | General | 125000 |
| June Sanders | Private | 22000 |
| John Barker | Sargeant | 45000 |
| Jim Castle | Sargeant | 38000 |
+--------------+----------+--------+
5 rows in set (0.01 sec)
If you group the results by rank, the output changes:
mysql> SELECT rank FROM people GROUP BY rank\g
+----------+
| rank |
+----------+
| General |
| Private |
| Sargeant |
+----------+
3 rows in set (0.01 sec)
Now that you have the output grouped, you can finally find out the
average salary for each rank. Again, we will discuss more on the
functions you see in this example later in the chapter.
mysql> SELECT rank, AVG(salary) FROM people GROUP BY rank\g
+----------+-------------+
| rank | AVG(salary) |
+----------+-------------+
| General | 125000.0000 |
| Private | 22500.0000 |
| Sargeant | 41500.0000 |
+----------+-------------+
3 rows in set (0.04 sec)