Group Results

API v58.0 and later

Group results using the groupBy argument. Results are grouped according to the field values within the record and the provided grouping function.

When querying a RecordAggregate, you can pass in an aggregate function and a groupBy argument. If you don't need aggregation, use the RecordQuery type instead.

The groupBy argument behaves like the SOQL GROUP BY clause. It can map elements to groups in three ways:

  • Using the distinct set of values you provide for the groupBy argument
  • Using the CUBE type
  • Using the ROLLUP type

Grouping is useful for summarizing your data based on a particular field. For example, when grouping by an Industry, passing in Industry to the groupBy argument clause assigns all Accounts that share an Industry to the same group, similar to a GROUP BY Industry SOQL clause.

The following field types support grouping. A Date/Time function can be applied to the field if it's a Date, Time, or DateTime function.

Group by ApiNameGroup by Date/Time Function

Group your results to avoid iterating through individual query results, specifying a group of records instead. You can use groupBy with aggregate functions like sum or max, which summarizes the data and enables you to roll up query results.

First, you can query the LeadSource without grouping, which returns a list of all lead sources on each lead, including duplicate values.

The previous query is similar to the following SOQL statement.

Instead of writing code to iterate through the query results and increment counters for each LeadSource value, you can use groupBy to return the same results.

The previous query is similar to the following SOQL statement.

You can also query all distinct values, including null, without an aggregated function.

The previous query is similar to the folowing SOQL statement.