Aggregates

SOQL GROUP BY

Grouping Results

SOQL GROUP BY groups records for aggregations like COUNT.

Introduction to SOQL GROUP BY

The SOQL GROUP BY clause allows you to group records that share a set of values, enabling you to perform aggregations such as counting, summing, or averaging on these groups. This is particularly useful when analyzing data and generating reports within Salesforce.

Basic Syntax of GROUP BY

The basic syntax for using the GROUP BY clause in SOQL is as follows:

In this syntax, fieldName is the field you are grouping on, and ObjectName is the name of the Salesforce object you are querying. The COUNT(Id) function is used to count the number of records in each group.

Example: Grouping by Industry

Let's consider a scenario where you want to see how many accounts are in each industry. You can achieve this using GROUP BY on the Industry field of the Account object:

This query will return the number of accounts for each industry type available in your Salesforce data.

Using Multiple Fields in GROUP BY

You can group records by more than one field by listing multiple fields in the GROUP BY clause. Here's how you can do it:

This query groups the accounts by both Industry and BillingCountry, providing a count of accounts for each combination of industry and country.

Considerations and Limitations

When using GROUP BY in SOQL:

  • Fields in the SELECT clause must either be aggregated or included in GROUP BY.
  • You cannot use ORDER BY on aggregated fields.
  • The maximum number of records returned by a SOQL query is 50,000. Consider using LIMIT to restrict results.

Understanding these limitations ensures that your queries are efficient and effective.

Previous
FOR UPDATE