GROUP BY

constructsupportedQueries & DML

docs.snowflake.com ↗

Groups rows with the same group-by-item expressions and computes aggregate functions for the resulting group. A GROUP BY expression can be: - A column name. - A number referencing a position in the SELECT list. - A general expression.

Syntax

supportedpartialnot supportednot scored

SELECT ...
  FROM ...
  [ ... ]
  GROUP BY groupItem [ , groupItem [ , ... ] ]
  [ ... ]
SELECT ...
  FROM ...
  [ ... ]
  GROUP BY ALL
  [ ... ]

Where

groupItem ::= { <column_alias> | <position> | <expr> }

Parameters

NameRequiredDescription
column_aliasColumn alias appearing in the query block’s SELECT list.
positionPosition of an expression in the SELECT list.
exprAny expression on tables in the current scope.
GROUP BY ALLSpecifies that all items in the SELECT list that do not use aggregate functions should be used for grouping. For examples, refer to Group by all columns.

Usage notes

GROUP BY extensions

GROUP BY supports the following extensions that provide powerful aggregation capabilities: - GROUP BY GROUPING SETS: Compute multiple GROUP BY clauses in a single statement - GROUP BY ROLLUP: Produce subtotal rows for hierarchical data - GROUP BY CUBE : Produce subtotal rows for all combinations of dimensions You can combine these extensions with regular GROUP BY columns. For example: - GROUP BY x, GROUPING SETS(y, z) - GROUP BY x, ROLLUP(y, z) - GROUP BY x, CUBE(y, z) For more information about interpreting NULL values in extension results, see the GROUPING utility function.

Parameters

column_alias: Column alias appearing in the query block’s SELECT list. position: Position of an expression in the SELECT list. expr: Any expression on tables in the current scope. GROUP BY ALL: Specifies that all items in the SELECT list that do not use aggregate functions should be used for grouping. For examples, refer to Group by all columns.

Precedence when a column name and an alias match

It is possible (but usually not recommended) to create a query that contains an alias that matches a column name: If a clause contains a name that matches both a column name and an alias, then the clause uses the column name. The following example demonstrates this behavior using a GROUP BY clause: Create a table and insert rows: The following query returns the sum of the salaries of the employees who are active and the sum of the salaries of the employees who are on leave: The next query uses the alias state, which matches the name of a column of the table in the query. When state is used in the GROUP BY clause, Snowflake interprets it as a reference to the column name, not the alias. This query therefore returns the sum of the salaries of the employees in the state of California and the sum of the salaries of the employees in the state of Oregon, yet displays employment_state information, such as Active, rather than the names of states or provinces: