Chapter 4. GROUP BY

Because GROUP BY can involve a sort, much of what we said about ORDER BY columns in the previous chapter applies for GROUP BY arguments too—keep 'em short and keep few of 'em. Beyond that, you should watch out for some other things when you write a grouping query. In this chapter, we'll look at optimizing GROUP BY and its related HAVING clause, as well as the SQL Standard set functions.

Refresher

The GROUP BY clause can explicitly appear in a SELECT statement, as in this example:

SELECT column1 FROM Table1
  GROUP BY column1

Grouping also happens implicitly if there is a HAVING clause or a set function, as in this example:

SELECT COUNT(*) FROM Table1
  HAVING COUNT(*) = 5

In standard SQL—and with InterBase and Microsoft—a GROUP BY ...

Get SQL Performance Tuning 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.