← All articles
Salesforce · SOQL · Quick Reads

SOQL Aggregate Functions: COUNT, SUM, AVG, MIN, MAX, and COUNT_DISTINCT

SOQL aggregate functions answer summary questions without returning every matching Salesforce record.

COUNT

SELECT COUNT(Id)
FROM Case
WHERE IsClosed = false

Use this when the question is simply how many records match.

COUNT_DISTINCT

SELECT COUNT_DISTINCT(AccountId)
FROM Opportunity
WHERE AccountId != null

This answers "how many unique Accounts have Opportunities?" without collecting Account IDs in application code.

SUM

SELECT SUM(Amount)
FROM Opportunity
WHERE IsClosed = false

AVG

SELECT AVG(Amount)
FROM Opportunity
WHERE IsWon = true

MIN and MAX

SELECT MIN(CloseDate), MAX(CloseDate)
FROM Opportunity
WHERE IsClosed = false

Combine with GROUP BY

Aggregates become more useful when segmented:

SELECT StageName,
       COUNT(Id),
       SUM(Amount),
       AVG(Amount)
FROM Opportunity
GROUP BY StageName

Aliases in Apex

Aggregate queries return AggregateResult values in Apex. Aliasing calculated expressions makes consuming them clearer:

SELECT StageName stage,
       COUNT(Id) opportunityCount,
       SUM(Amount) pipeline
FROM Opportunity
GROUP BY StageName

Then retrieve the alias from each AggregateResult rather than relying on generated expression names.

Push the Right Work to Salesforce

If your application only needs a count or total, querying thousands of rows to compute it elsewhere increases network traffic and application work. Aggregation is often the cleaner boundary.

Do not confuse that with analytics workloads that require huge multidimensional datasets. SOQL has governor and query limits; use the right Salesforce analytics/data capability for the scale and purpose.

References

CONTINUE READING

Explore closely related architecture, integration and implementation topics.