Grouping Data

Grouping is a SQL feature that enables you to produce summary data on groups of rows in the result set.

Consider the first example in this lesson, in which you performed a query using COUNT(*) to find the total number of orders in the database. Suppose that now you want to know the total number of orders for each customer.

By adding a WHERE clause, you could restrict the count using a customer_code value, but you would have to perform this query once for each customer to find all the totals. By grouping data instead, you can perform the aggregate function for each customer in a single query.

The GROUP BY Clause

To tell MySQL how to group the data in a query, you add a GROUP BY clause. This must appear after the WHERE clause and ...

Get Sams Teach Yourself MySQL 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.