SOQL Aggregate Functions
The SOQL aggregate functions are used to calculate and return a single value by aggregating the data of a field FROM the returned SOQL records. Aggregate functions are similar to pivot table in Excel.
Aggregate functions can be used to count records, sum numeric field in the returned records, or to return the minimum and the maximum number or date from the returned data.
The SOQL aggregate functions can also be used to generate simplified reports using the GROUP BY
clause, by aggregating data in various categories.
For example, you can get the number of clinics for each state, or region.
Count(ID) | State |
---|---|
120 | Florida |
10 | Illinois |
28 | Nevada |
We get here, the number of clinics for each state. The rows above are also called as aggregated rows.
Let’s take a look at all the aggregate functions supported in SOQL:
SOQL COUNT
COUNT() is used to find the total count of returned rows in SOQL. COUNT(field_name) is used to find the total count of rows which contain non null field values.
Example #1: Find the count of appointments in the previous month.
Example #2: Find the count of patients who have an email address present in Salesforce.
Example #3: Find the count of clinics by various states.
SOQL AVG
To find the average of values in a field returned by SOQL. This operator can only be used with Number fields.
Example: Find the average booking amount earned by appointments in various clinics in the previous month.
SOQL SUM
To find the sum of values in a field returned by SOQL. This operator can only be used with Number fields.
Example: Find the total booking amount earned by appointments in various clinics in the previous month.
SOQL MIN
To find the minimal field value in the records returned by SOQL. This operator can only be used with Number fields.
Example: Find the oldest patient’s birthdate for KMG.
SOQL MAX
To find the mimaximal field value in the records returned by SOQL. This operator can only be used with Number fields.
Example: Find the maximum booking amount charged on a single appointment by each clinic in previous month.
>GROUP BY
clause, all the fields which are fetched, must either be grouped or aggregated.