Sub topic 1
What Aggregate Queries Do and When to Use Them
Prerequisites
This chapter assumes you know basic SOQL, including SELECT, FROM, and WHERE. You should also know common Salesforce objects such as Account, Lead, and Opportunity, plus basic Apex loops and type casting.
What Aggregate Queries Do
An aggregate query summarizes many records into calculated values. It can answer questions such as “How many leads came from each source?” or “What is the average opportunity amount?” The query returns summary rows instead of complete Salesforce records.
Use aggregate queries for reports, dashboards, data checks, and efficient calculations. They avoid retrieving every record when you only need totals or counts.
Counting Records
COUNT counts records. COUNT(Id) is a common form:
SELECT COUNT(Id) leadCount
FROM LeadThe alias leadCount gives the calculated value a readable name.
COUNT_DISTINCT counts different non-null values in a field:
SELECT COUNT_DISTINCT(Industry) industryCount
FROM AccountThis returns the number of distinct industries used by accounts. It does not count blank values.
Summarizing Values
Use SUM for a total, AVG for an average, and MIN or MAX for the smallest or largest value. These functions commonly operate on numeric fields such as Amount.
SELECT
SUM(Amount) totalAmount,
AVG(Amount) averageAmount,
MIN(Amount) smallestAmount,
MAX(Amount) largestAmount
FROM Opportunity
WHERE IsClosed = falseWHERE limits the records included in the calculations. Null field values are generally ignored by these functions.
Grouping Results with GROUP BY
GROUP BY creates one summary row for each distinct value of a field:
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSourceThe result contains one row per lead source. You can group by multiple fields when each combination matters:
SELECT StageName, IsClosed, COUNT(Id) recordCount
FROM Opportunity
GROUP BY StageName, IsClosedEvery selected field that is not inside an aggregate function must appear in GROUP BY.
Exercise
Which query returns one row for each account industry with its average opportunity amount?
Show answer
SELECT Account.Industry, AVG(Amount) averageAmount FROM Opportunity GROUP BY Account.Industry