The GROUP BY clause denotes that rows should be grouped according to the specified expression values. One row will be returned for each group, after optionally filtering those aggregate rows based on a HAVING clause.

The general form of the GROUP BY clause is as follows:

  • GROUP BY expression (,expression)

Syntax Rules:

  • Column references in the group by clause must by to unaliased output columns;
  • Expressions used in the group by clause must appear in the SELECT clause;
  • Column references and expressions in the select clause that are not used in the group by clause must appear in aggregate functions;
  • If an aggregate function is used in the SELECT clause and no GROUP BY is specified, an implicit GROUP BY will be performed with the entire result set as a single group. In this case, every column in the SELECT clause must be an aggregate function as no other column value will be fixed across the entire group;
  • The group by columns must be of a comparable type.