The GROUP BY Clause

As you discovered in Chapter 12, you can find out all sorts of interesting information by using aggregate functions. However, you might have noticed that all the examples we gave you applied the aggregate functions across all the rows returned by the FROM and WHERE clauses. You could filter the result set down to one group using the WHERE clause, but there was really no way to look at the results from multiple groups in one request. To accomplish this summarizing by group in a single request, we need to add one more major clause to your SQL vocabulary—GROUP BY.


Let’s take a close look at the GROUP BY clause. Figure 13-1 shows the basic diagram for a SELECT statement with GROUP BY added.

Figure 13-1. The syntax diagram ...

Get SQL Queries for Mere Mortals: A Hands-On Guide to Data Manipulation in SQL, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.