Sub topic 15
How Reports Relate to SOQL Aggregate Queries
This chapter assumes you can build a summary report and a matrix report, and that you know what an object, a record, and a field are. You do not need to write Apex. Basic SELECT and WHERE syntax helps, but each query is explained.
By the end you will be able to read a summary or matrix report as a SOQL aggregate query. You will also know where the two stop matching, so you can check a report's numbers in Developer Console or Workbench.
Why compare reports with SOQL
SOQL (Salesforce Object Query Language) is the query language for reading Salesforce records. A report is a saved, point-and-click question about records. An aggregate query is a SOQL query that groups records and calculates a number for each group.
The two ideas line up closely:
| Report concept | SOQL concept |
|---|---|
| Report type (primary object) | `FROM` object |
| Filters and scope | `WHERE` clause |
| Row grouping | `GROUP BY` field |
| Column grouping (matrix) | Second field in `GROUP BY` |
| Sum, average, min, max, record count | `SUM()`, `AVG()`, `MIN()`, `MAX()`, `COUNT()` |
| Filter on a summary value | `HAVING` clause |
| Sort by a group or summary | `ORDER BY` |
Knowing this mapping helps in three ways. You can verify a surprising report number by running the equivalent query. You can see why a report behaves as it does, for example why empty groups do not appear. And you can decide whether a question belongs in a report or in code.
A summary report as a query
Take a summary report on Opportunities. It is grouped by Stage, and it shows the sum of Amount and the record count. The equivalent query is:
SELECT StageName, SUM(Amount) total, COUNT(Id) cnt
FROM Opportunity
GROUP BY StageNameEach part maps to a report setting:
FROM Opportunityis the report type's primary object.GROUP BY StageNameis the row grouping. Each distinct stage produces one result row, which is the same as one group in the report.SUM(Amount) totalis the summarized field Amount with Sum selected.COUNT(Id) cntis Record Count.
The aliases total and cnt are names you choose. Without an alias, SOQL names unaliased aggregates expr0, expr1, and so on.
The query returns one row per stage. The report shows those same rows as group headings, and each group also lists its detail records. The query returns only the summary rows. To see the details, you would run a second, non-aggregate query.
Adding filters
Report filters become a WHERE clause. If the report filters on Close Date in the current fiscal year and Amount greater than zero, the query becomes:
SELECT StageName, SUM(Amount) total, COUNT(Id) cnt
FROM Opportunity
WHERE CloseDate = THIS_FISCAL_YEAR AND Amount > 0
GROUP BY StageNameSOQL date literals such as THIS_FISCAL_YEAR match the relative ranges in the report filter menu. A filter on a summary value, such as "only stages whose total is above 100,000," is a HAVING clause:
SELECT StageName, SUM(Amount) total
FROM Opportunity
GROUP BY StageName
HAVING SUM(Amount) > 100000In a report, you get the same result with a filter on the summary field, or you hide groups by using a chart or dashboard setting. The query version is explicit about it.
A matrix report as a query
A matrix report groups by rows and by columns. A matrix with Stage as rows and Close Year as columns corresponds to a query with two grouping expressions:
SELECT StageName, CALENDAR_YEAR(CloseDate) yr, SUM(Amount) total
FROM Opportunity
GROUP BY StageName, CALENDAR_YEAR(CloseDate)Each result row is one cell of the matrix. A row such as Closed Won, 2026, 450000 is the cell where the Closed Won row meets the 2026 column.
Two details matter here.
- SOQL returns the data in a flat list, not a grid. Your code or a spreadsheet must pivot it into rows and columns. The report builder does the pivot for you.
- The query has no subtotals. A matrix shows row totals, column totals, and a grand total. In SOQL, you get the same totals with
GROUP BY ROLLUP, or by running a separate query with fewer grouping fields.
Totals with ROLLUP
GROUP BY ROLLUP adds subtotal rows to the result. Subtotal rows contain null in the grouping fields that were rolled up.
SELECT StageName, CALENDAR_YEAR(CloseDate) yr, SUM(Amount) total
FROM Opportunity
GROUP BY ROLLUP(StageName, CALENDAR_YEAR(CloseDate))This returns the detail rows, a subtotal for each stage (year is null), and a grand total (both are null). Use GROUPING(StageName) in the select list to tell a real null value from a subtotal row.
SELECT StageName, GROUPING(StageName) isStageTotal, SUM(Amount) total
FROM Opportunity
GROUP BY ROLLUP(StageName)GROUPING returns 1 for a subtotal row and 0 for an ordinary row.
The data flow
Both a report and a query go through the same logical steps. The diagram shows the order.
Filtering happens before grouping. That is why changing a filter changes the totals, not just which rows you see.
Where reports and SOQL differ
The mapping is close but not exact. These differences cause most mismatches when you compare numbers.
Record visibility
A report runs as the person viewing it, and sharing rules limit the records it sees. A query run in Developer Console also respects your own access. A query in Apex may not. Apex runs in system mode by default, so it can see records you cannot, unless the class uses with sharing. Before comparing totals, make sure both sides use the same user and the same scope. A report scope such as "My opportunities" has no direct counterpart unless you add WHERE OwnerId = :UserInfo.getUserId() in Apex or the literal user ID in the console.
Null handling
Aggregate functions ignore null values. SUM(Amount) skips records with no Amount, and AVG(Amount) divides by the number of records that have an Amount. COUNT(Id) counts all records, but COUNT(Amount) counts only the records where Amount is not null. In a report, Record Count counts every record. The report's Average on a field also skips blanks.
This explains a common mismatch. A custom summary formula such as the one below divides by all records in the group, including those with no Amount:
AMOUNT:SUM / RowCountThe built-in Average of Amount divides by only the records that have an Amount. The two numbers differ when some Amounts are blank. Neither is wrong. They answer different questions.
Previous-group comparisons
Some report features have no direct SOQL form. This formula, in a report grouped by Close Date, shows the change in summed Amount against the previous group:
AMOUNT:SUM - PREVGROUPVAL(AMOUNT:SUM, CLOSE_DATE)SOQL has no PREVGROUPVAL. You would run the grouped query, sort the rows by date, and subtract the previous row's total in code. Window functions like this belong in the layer that consumes the results.
Joined reports
A joined report has several blocks, and each block has its own report type. It is not a single query. It behaves like several queries whose results are shown side by side and matched on a common grouping. SOQL has no direct equivalent. You run one aggregate query per block and merge the results by the shared key in code.
Result limits
SOQL aggregate queries have limits that reports handle differently. In Apex, a query that has no LIMIT returns up to 2,000 rows in an aggregate query that groups by fields, and governor limits cap the total rows retrieved per transaction. A report shows up to 2,000 detail rows in the browser, and it calculates summaries over all matching records. Check current limits in the Salesforce documentation, because they change between releases.
Checking a report with a query
A practical workflow for verifying a report:
- Write down the report type, the filters, the scope, the groupings, and the summarized fields.
- Translate them into
FROM,WHERE,GROUP BY, and aggregate functions. - Run the query as the same user who runs the report.
- Compare group by group. If a group is missing or a total differs, check null Amounts, the filter logic, and the scope first.
When to use each
Use a report when users need to explore, filter, and chart data without code. Use an aggregate query when the numbers feed an Apex process, an integration, or a custom component. Queries also let you put calculations in code that reports cannot express. If a report is slow or hits a limit, compare it with the query. The comparison often reveals an unselective filter.
Exercise
A summary report on Opportunities is grouped by Stage and shows Sum of Amount and Record Count. You run the query SELECT StageName, SUM(Amount) FROM Opportunity GROUP BY StageName in Developer Console and one stage's total is higher than the report's. List two likely causes.
Show answer
First, the report may have a filter or scope (for example "My opportunities" or a date range) that the query does not have, so the query includes more records. Second, the report runs as a user with limited record access, while the query may run with different visibility, so the two see different sets of records. A third possibility is a different set of null or zero Amounts, but nulls do not raise a SUM, so filters and visibility are the first things to check.
Exercise
Write a SOQL query equivalent to a matrix report on Opportunities with Type as rows, Stage as columns, and Record Count as the summary. Explain what one result row represents.
Show answer
SELECT Type, StageName, COUNT(Id) cnt FROM Opportunity GROUP BY Type, StageName. Each result row is one cell of the matrix: the count of opportunities with that Type and that Stage. Row and column totals are not included unless you use GROUP BY ROLLUP or run separate queries.