GROUP BY and ORDER BY

GROUP BY divides tables into sets of rows, but it doesn't necessarily put those sets in any order. If you want your results sorted in some particular way, use ORDER BY (see “ORDER BY Syntax” in Chapter 5). Remember that the sequence of clauses in SELECT statements is fixed, and ORDER BY always goes after GROUP BY. For example, to find the average price for books of each type with advances over $5,000 and order the results by average price, the statement is this:

SQL
select type, avg(price)
from titles
where advance > 5000
group by type
order by 2
type         avg(titles.price)
============ =================
business                 12.99
mod_cook                 12.99
psychology               29.30
trad_cook                35.47
popular_comp             41.48
[5 rows]

Get Practical SQL Handbook, The: Using SQL Variants, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.