Sub topic 5
Naming Aggregate Results with Aliases
This chapter assumes you know basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT), understand Salesforce objects and field types, and can read simple Apex with variables, loops, and casting. You have already seen COUNT, SUM, and GROUP BY. Here you will learn how to name the aggregate columns in a result, why naming matters, and which errors come from getting it wrong.
Why aggregate expressions need names
A plain SOQL query returns sObject records, and each field has a fixed name such as Name or Amount. An aggregate expression such as COUNT(Id) does not match any field on the object. SOQL has to label that column some other way.
If you give no alias, SOQL assigns a default name of the form expr0, expr1, and so on. The number is the position of the unaliased aggregate expression in the SELECT list, counting from zero. Fields you group by keep their own field names.
SELECT LeadSource, COUNT(Id), MAX(AnnualRevenue)
FROM Lead
GROUP BY LeadSourceIn this query the result columns are named LeadSource, expr0, and expr1. The names are valid, but they say nothing about what the numbers mean. If you later add or reorder an aggregate, the numbering shifts and any Apex code that reads expr1 silently reads a different value.
An alias is a name you write directly after the expression, separated by a space. It does not use AS.
SELECT LeadSource, COUNT(Id) leadCount, MAX(AnnualRevenue) topRevenue
FROM Lead
GROUP BY LeadSourceNow the columns are LeadSource, leadCount, and topRevenue. Those names stay the same if you reorder the SELECT list.
Alias syntax
The alias goes immediately after the closing parenthesis of the function:
SELECT COUNT_DISTINCT(Industry) industryCount
FROM AccountKeep these rules in mind.
- Write the alias after a space. SOQL does not accept the SQL keyword
ASin this position, soCOUNT(Id) AS cntis a syntax error. - An alias is a simple identifier. Use letters, digits, and underscores, and start with a letter.
- Do not reuse a reserved word or a field name from the same query as an alias. Names such as
IdorNameconfuse the query and can cause an error or an ambiguous read. - Alias names are not case sensitive in the query, but pick one casing and use the same casing in Apex so the code is easier to search.
- Each alias in a query must be unique.
Aliases are only for aggregate expressions. You cannot alias a plain field such as LeadSource. Grouped fields keep the name of the field itself. For a related field such as Account.Industry, the result key is the full path Account.Industry.
When aliases are required and when they are optional
In the Developer Console or Workbench, unaliased columns display as expr0 and work fine for a quick look. Aliases become important in three situations.
- Apex code reads the results.
AggregateResult.get()takes the column name as a string, so a stable alias is the easiest way to read each value. - A query has several aggregates. With one aggregate,
expr0is easy to guess. With four, a name liketotalAmountis much clearer. - The same function is used twice. For example,
MIN(Amount)andMAX(Amount)produce two different columns. Aliases keep them apart.
Make aliases a habit in every aggregate query that code will read.
Default names are positional
The default numbering is easy to misread, so it is worth a careful look. Only unaliased aggregate expressions are counted, and the counter starts at zero.
SELECT StageName, COUNT(Id) cnt, SUM(Amount), AVG(Amount)
FROM Opportunity
GROUP BY StageNameHere COUNT(Id) has an alias, so it does not use a default name. SUM(Amount) becomes expr0, and AVG(Amount) becomes expr1. A reader who assumed that SUM(Amount) was expr1 because it is the third item would read the wrong column.
If you mix aliased and unaliased expressions, you lose the main benefit of aliases, which is that the names carry meaning. Alias all of them or none of them.
The positional numbering is shown in the diagram below.
Reading aliased columns in Apex
In Apex, a grouped query returns a list of AggregateResult objects. Each object represents one row. You read a column by calling get() with the field name or alias, and you cast the returned value, because get() returns Object.
for (AggregateResult ar : [
SELECT StageName, COUNT(Id) cnt, SUM(Amount) total
FROM Opportunity
GROUP BY StageName
]) {
String stage = (String) ar.get('StageName');
Integer cnt = (Integer) ar.get('cnt');
Decimal total = (Decimal) ar.get('total');
System.debug(stage + ': ' + cnt + ' opportunities, total ' + total);
}The strings passed to get() must match the names in the query. Apex checks them only at run time. If you misspell 'cnt' as 'count', the code compiles, and you get a System.QueryException or a null value when the line runs. Unit tests that cover the loop catch this early.
The next chapter covers AggregateResult in more detail. Here the important point is that the alias is the contract between the query and the code.
Casting the values
The type returned by get() depends on the aggregate function, so the cast needs care.
| Expression | Typical Apex type to cast to |
|---|---|
| `COUNT(Id)`, `COUNT()` with a field | `Integer` |
| `COUNT_DISTINCT(field)` | `Integer` |
| `SUM(Amount)` on a currency field | `Decimal` |
| `AVG(Amount)` | `Decimal` (or `Double` for some number fields) |
| `MIN` or `MAX` on a date field | `Date` |
| `MIN` or `MAX` on a text field | `String` |
If you are unsure, assign the value to Object first and print it with System.debug. A wrong cast throws a System.TypeException at run time. For number fields where the type is not obvious, a safe approach is to cast to Decimal, because Apex converts between numeric types when you assign them.
Aliases and the other clauses
Aliases appear in the SELECT list. Their use in other clauses is limited, and this is a common source of confusion.
HAVING and ORDER BY
In SOQL, the HAVING clause repeats the aggregate expression. It does not accept the alias.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000Writing HAVING total > 100000 fails, because total is a label for an output column and not a field the query can filter on. Repeat SUM(Amount) instead.
ORDER BY follows the same pattern. Order by the expression itself, as in ORDER BY SUM(Amount) DESC. Chapter 9 covers ordering in full.
Grouping by a date function
When you group by a date function, the function call appears in the SELECT list, and you can alias it. The GROUP BY and ORDER BY clauses must repeat the function call.
SELECT CALENDAR_YEAR(CloseDate) yr, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY CALENDAR_YEAR(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate)The alias yr is the name Apex uses in ar.get('yr'). Without the alias, the function value would get a default name such as expr0, and a reader of the Apex code would not know what it holds.
A worked example
Suppose a sales manager wants, for each lead source, the number of leads, the number of distinct industries, and the highest annual revenue. The query uses three aliases.
SELECT LeadSource,
COUNT(Id) leadCount,
COUNT_DISTINCT(Industry) industryCount,
MAX(AnnualRevenue) topRevenue
FROM Lead
GROUP BY LeadSourceThe Apex that reads it can then be self-explanatory:
List<AggregateResult> rows = [
SELECT LeadSource,
COUNT(Id) leadCount,
COUNT_DISTINCT(Industry) industryCount,
MAX(AnnualRevenue) topRevenue
FROM Lead
GROUP BY LeadSource
];
for (AggregateResult ar : rows) {
String source = (String) ar.get('LeadSource');
Integer leads = (Integer) ar.get('leadCount');
Integer industries = (Integer) ar.get('industryCount');
Decimal topRevenue = (Decimal) ar.get('topRevenue');
System.debug(source + ' | leads: ' + leads
+ ' | industries: ' + industries
+ ' | top revenue: ' + topRevenue);
}Note that LeadSource can be null for leads that have no source. The cast (String) ar.get('LeadSource') returns null for that group, so the debug line prints null. Handle that case if you display or store the value.
Common errors with aliases
| Symptom | Cause | Fix |
|---|---|---|
| Syntax error near `AS` | The SQL keyword `AS` is not valid before an alias | Remove `AS` and write `COUNT(Id) cnt` |
| `get()` returns null or throws for a name | The string does not match the alias, or the alias was never defined | Match the string to the alias exactly, and add a test |
| Code reads the wrong number after a query edit | The code relied on `expr0` or `expr1` and the SELECT list changed | Add explicit aliases to every aggregate |
| `HAVING` or `ORDER BY` rejects the alias | These clauses need the expression itself | Repeat the aggregate expression |
| Error about a duplicate or reserved name | The alias repeats another alias, or is a field name or keyword | Choose a distinct descriptive name such as `leadCount` |
| `System.TypeException` on cast | The cast does not match the value type | Check the type in the table, or cast to `Decimal` for numbers |
Summary
- Aggregate columns without aliases get positional names
expr0,expr1, and so on. Only unaliased aggregates are counted. - An alias goes after the expression with a space. Do not use
AS. - Apex reads a column with
ar.get('alias')and casts the result. HAVINGandORDER BYrepeat the expression and do not accept the alias.- Alias every aggregate that code reads. Use meaningful, unique names.
Exercise
A query reads SELECT StageName, COUNT(Id) cnt, SUM(Amount), AVG(Amount) FROM Opportunity GROUP BY StageName. In Apex, which name do you pass to ar.get() to read the average amount, and what change makes the query safer to maintain?
Show answer
The average has no alias, so it is the second unaliased aggregate and is named expr1 (SUM(Amount) is expr0, and COUNT(Id) is excluded because it has the alias cnt). Safer: give both aggregates aliases, for example SUM(Amount) total, AVG(Amount) avgAmount, and read them with ar.get('total') and ar.get('avgAmount').
Exercise
Why does SELECT AccountId, SUM(Amount) total FROM Opportunity GROUP BY AccountId HAVING total > 100000 fail, and how do you correct it?
Show answer
HAVING cannot use an alias, because the alias only names an output column. Repeat the aggregate expression: HAVING SUM(Amount) > 100000. The alias total can stay in the SELECT list so Apex can read it with ar.get('total').