Aggregates

SOQL AVG Function

Using AVG Function

SOQL AVG function calculates average of numeric fields.

Introduction to the SOQL AVG Function

The AVG function in SOQL (Salesforce Object Query Language) is used to calculate the average of numeric fields in your Salesforce data. This function is particularly useful when you need to analyze data trends and summarize information over a set of records. Understanding how to use the AVG function efficiently can enhance your data analysis capabilities within Salesforce.

Syntax of the AVG Function

The syntax of the AVG function in SOQL is straightforward. It is used within a SELECT statement and combined with the GROUP BY clause when needed. Here is the basic syntax:

The NumericField represents the field whose average you wish to calculate, and ObjectName is the name of the Salesforce object containing the field.

Example: Calculating Average Account Revenue

Let's consider an example where you want to find the average annual revenue of all accounts in your Salesforce instance. Here is how you would use the AVG function:

This query calculates the average annual revenue across all Account records. It's a powerful way to quickly summarize financial data.

Using AVG with GROUP BY

The AVG function can be even more effective when used with the GROUP BY clause. This allows you to calculate averages for different subsets of data. For example, you might want to calculate the average revenue by industry:

In this query, the average annual revenue is calculated for each industry type, providing insights into how different sectors are performing.

Considerations When Using AVG

  • The AVG function only works with numeric fields. Ensure your field type is numeric to avoid errors.
  • Null values in the field are ignored in the average calculation.
  • The AVG function can be used in combination with other aggregate functions for more complex queries.