20.6. Sorting and GROUP BY

Though it is not required by the standard, most implementations will automatically sort the results of a grouped query. Internally, the groups were built by first sorting the table on the grouping columns and then aggregating them. The NULL group can sort either high or low, depending on the vendor.

An ORDER BY clause whose columns are not in the same order as those in the GROUP BY clause can be expensive to execute if the optimizer does not ignore the extra sort request. It is also possible to sort a grouped table on an aggregate or calculated column. For example, to show the Sales regions in order of total Sales, you would write:

SELECT region, district, SUM(sales_amt) AS district_sales_amt FROM Sales GROUP BY region, ...

Get Joe Celko's SQL for Smarties, 3rd 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.