Home > Articles > Data > SQL

SELECT Statement: The GROUP BY Clause in SQL

  • Print
  • + Share This
Rick F. van der Lans explains how SQL's GROUP BY clause groups rows on the basis of similarities between them. He goes on to explain the use of adding aggregation functions to display summations, averages, frequencies, and subtotals.
This chapter is from the book

10.1 Introduction

The GROUP BY clause groups rows on the basis of similarities between them. You could, for example, group all the rows in the PLAYERS table on the basis of the place of residence; the result would be one group of players per town. From there you could query how many players there are in each group. The question that is actually answered is then: How many players live in each town? Other examples follow: How many matches have been played per team, and how much has been incurred in penalties per player? In short, the GROUP BY clause is frequently used to formulate questions based on the word per.

By adding aggregation functions, such as COUNT and SUM, to a select block with the use of a GROUP BY clause, data can be aggregated. These functions owe their name to this. Aggregation means that you ask not for the individual values, but for summations, averages, frequencies, and subtotals.

<group by clause> ::=
   GROUP BY <group by specification list>
            [ WITH { ROLLUP | CUBE } ]

<group by specification list> ::=
   <group by specification> [ { , <group by specification> }... ]

<group by specification> ::=
   <group by expression>         |
   <grouping sets specification> |
   <rollup specification>

<grouping sets specification> ::=
   GROUPING SETS ( <grouping sets specification list> )
<grouping sets specification list> ::=
   <grouping sets specification>
   [ { , <grouping sets specification> }... ]

<grouping sets specification> ::=
   <group by expression>                 |
   <rollup specification>                |
   ( <grouping sets specification list> )

<rollup specification> ::=
   ROLLUP ( <group by expression list> ) |
   CUBE ( <group by expression list> )   |
   ( )

<group by expression> ::= <scalar expression>
  • + Share This
  • 🔖 Save To Your Account