O'Reilly logo

Sams Teach Yourself MySQL by Chris Newman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required