Grouping and Sorting

It is important to understand that GROUP BY and ORDER BY are very different, even though they often accomplish the same thing. Table 10.1 summarizes the differences between them.

Table 10.1. ORDER BY Versus GROUP BY
ORDER BYGROUP BY
Sorts generated outputGroups rows. The output might not be in group order, however.
Any columns (even columns not selected) or may be usedOnly selected columns or expressions or may be used, and every selected column expression must be used.
Never requiredRequired if using columns (or expressions) with aggregate functions.

The first difference listed in Table 10.1 is extremely important. More often than not, you will find that data grouped using GROUP BY will indeed be output in group order. But ...

Get Sams Teach Yourself SQL in 10 Minutes 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.