Skip to main content

GROUP BY

Group rows by one or more columns and apply aggregate functions to each group:
Multiple grouping columns:
Positional ordinals are also supported. GROUP BY 1, 2 groups by the first and second select-list expressions:
Grouping expressions are also supported directly:

HAVING

Filter groups after aggregation. You can use both aggregate and non-aggregate predicates:

Aggregate Functions

DISTINCT Aggregates

Deduplicate values before aggregating:

Using Aliases in ORDER BY

Aliases defined in the SELECT list are available in ORDER BY. They cannot be used in GROUP BY or HAVING — repeat the expression there instead.

GROUPING SETS

GROUPING SETS lets you compute aggregates for multiple grouping combinations in a single query. Columns not part of a given grouping set are returned as NULL:

ROLLUP

ROLLUP creates subtotals that roll up from the most detailed level to a grand total. ROLLUP(a, b) is equivalent to GROUPING SETS((a, b), (a), ()):

CUBE

CUBE generates subtotals for all possible combinations of the grouping columns. CUBE(a, b) is equivalent to GROUPING SETS((a, b), (a), (b), ()):

Not Supported

  • Window functions (ROW_NUMBER, RANK, SUM OVER, etc.)