Sub topic 11
Grouping by calendar and fiscal date parts
This chapter assumes you can write basic SOQL with SELECT, WHERE, and ORDER BY, and that you know the basic aggregate functions and GROUP BY. You should also be comfortable with Apex loops and casting.
Why group by date parts
A date field such as CloseDate holds a full day. If you group by it directly, you get one row per distinct day. That is rarely what a report needs. Most summaries ask for totals per year, per quarter, or per month.
SOQL provides date functions that turn a date or datetime into a single number, such as the year or the month. You can use these functions in SELECT, GROUP BY, HAVING, WHERE, and ORDER BY. Each distinct number becomes one group.
Calendar date functions
The calendar functions use the standard January-to-December year.
| Function | Returns | Example result |
|---|---|---|
| `CALENDAR_YEAR(field)` | Four-digit year | 2026 |
| `CALENDAR_QUARTER(field)` | Quarter, 1 to 4 | 3 |
| `CALENDAR_MONTH(field)` | Month, 1 to 12 | 11 |
| `DAY_IN_MONTH(field)` | Day of month, 1 to 31 | 30 |
| `DAY_IN_WEEK(field)` | Day of week, 1 (Sunday) to 7 (Saturday) | 2 |
| `DAY_IN_YEAR(field)` | Day of year, 1 to 366 | 334 |
| `WEEK_IN_MONTH(field)` | Week of month, 1 to 5 | 5 |
| `WEEK_IN_YEAR(field)` | Week of year, 1 to 53 | 49 |
Each function returns an integer. It does not return a date. The value 11 from CALENDAR_MONTH means November of some year, and nothing in the number says which year.
A first example: totals per year
The following query totals won opportunity amounts per calendar year.
SELECT CALENDAR_YEAR(CloseDate) yr, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY CALENDAR_YEAR(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate)Three points about this query:
- The expression in
SELECTmust match the expression inGROUP BY. SelectingCALENDAR_YEAR(CloseDate)and grouping byCloseDateis an error, because the selected value is not the grouping value. - The alias
yrnames the column in the result. You will need it in Apex, as shown later. ORDER BYrepeats the function call. Salesforce does not let you order by the alias, so you write the expression again.
Grouping by more than one date part
Grouping by month alone merges every January from every year. To get a monthly time series, group by year and month together.
SELECT CALENDAR_YEAR(CloseDate) yr,
CALENDAR_MONTH(CloseDate) mth,
COUNT(Id) cnt,
SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)Each row now represents one month of one year. The ORDER BY lists the year first so the rows come out in time order.
Fiscal date functions
Many companies use a fiscal year that does not match the calendar year. For example, a fiscal year may start in April. Salesforce stores the fiscal year setting for your org. The fiscal functions read that setting.
| Function | Returns |
|---|---|
| `FISCAL_YEAR(field)` | Fiscal year |
| `FISCAL_QUARTER(field)` | Fiscal quarter, 1 to 4 |
| `FISCAL_MONTH(field)` | Fiscal month, 1 to 12 |
Here is a query that totals won amounts per fiscal year and quarter.
SELECT FISCAL_YEAR(CloseDate) fy,
FISCAL_QUARTER(CloseDate) fq,
SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY FISCAL_YEAR(CloseDate), FISCAL_QUARTER(CloseDate)
ORDER BY FISCAL_YEAR(CloseDate), FISCAL_QUARTER(CloseDate)Fiscal month 1 is the first month of the fiscal year, not January. With an April start, a close date in April gives FISCAL_MONTH of 1. Which fiscal year an April date belongs to depends on how the org names its fiscal years, so check your fiscal year settings before you trust the labels.
Datetime fields and time zones
Some fields, such as CreatedDate, are datetimes and are stored in UTC. When you apply a date function to a datetime field, the result is based on the running user's time zone, not UTC. A record created at 23:30 UTC on 30 November counts as 1 December for a user whose time zone is several hours ahead.
This has two consequences:
- The same query can give different group boundaries for users in different time zones.
- Records near midnight or near a month end can land in a different group than you expect.
If you need a fixed boundary regardless of user, use a date field instead of a datetime field, or apply convertTimezone() inside the date function. The next query groups by the month in which a record was created, using the user's time zone.
SELECT CALENDAR_MONTH(convertTimezone(CreatedDate)) mth, COUNT(Id) cnt
FROM Lead
GROUP BY CALENDAR_MONTH(convertTimezone(CreatedDate))
ORDER BY CALENDAR_MONTH(convertTimezone(CreatedDate))The convertTimezone() function works only inside a date function. It makes the conversion explicit in the query, which helps readers see what the query does.
Reading date groups in Apex
Date functions return numbers, and AggregateResult.get() returns Object. Cast the value to Integer. The alias is the key you pass to get().
for (AggregateResult ar : [
SELECT CALENDAR_YEAR(CloseDate) yr,
CALENDAR_MONTH(CloseDate) mth,
SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)
]) {
Integer yr = (Integer) ar.get('yr');
Integer mth = (Integer) ar.get('mth');
Decimal total = (Decimal) ar.get('total');
System.debug(yr + '-' + mth + ': ' + total);
}Without aliases, Salesforce names the columns expr0, expr1, and so on. That works, but the code is harder to read, and the names change if you reorder the fields. Always alias date expressions.
If Amount is null for every record in a group, SUM(Amount) returns null, so a cast to Decimal gives a null value. Guard against this if you do arithmetic on the result.
Combining date groups with WHERE and HAVING
Use WHERE to restrict which records enter the grouping. Date literals work well here, because they let you limit the range without hard-coded dates.
SELECT CALENDAR_MONTH(CloseDate) mth, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true AND CloseDate = THIS_YEAR
GROUP BY CALENDAR_MONTH(CloseDate)
HAVING SUM(Amount) > 50000
ORDER BY CALENDAR_MONTH(CloseDate)The WHERE clause keeps only opportunities won this year. After grouping, HAVING keeps only the months whose total is above 50000. Months with no won opportunities do not appear at all. SOQL does not fill gaps, so if you need all twelve months, add the missing ones in Apex.
Common errors
- Selecting a date function that is not grouped.
SELECT CALENDAR_YEAR(CloseDate), COUNT(Id) FROM Opportunitywithout aGROUP BYclause raises an error. Add the matchingGROUP BY. - Grouping by month without year. The query runs, but January 2025 and January 2026 merge into one row.
- Ordering by the alias. Repeat the full expression in
ORDER BY. - Assuming fiscal equals calendar. Compare both on a few known records before you rely on fiscal output.
- Ignoring user time zone on datetime fields. Results can shift near boundaries.
- Casting to the wrong type. The date functions return
Integer. Casting toDecimalorStringfails or gives surprises.
Choosing between calendar and fiscal grouping
| Need | Use |
|---|---|
| Public reporting by calendar year | `CALENDAR_YEAR`, `CALENDAR_QUARTER` |
| Internal finance reporting that matches the company's fiscal calendar | `FISCAL_YEAR`, `FISCAL_QUARTER` |
| Seasonal patterns across years, such as "all Decembers" | `CALENDAR_MONTH` alone |
| A continuous monthly time series | `CALENDAR_YEAR` plus `CALENDAR_MONTH` |
| Weekday patterns | `DAY_IN_WEEK` |
Exercise
You run SELECT CALENDAR_MONTH(CloseDate) mth, SUM(Amount) total FROM Opportunity WHERE IsWon = true GROUP BY CALENDAR_MONTH(CloseDate) over three years of data and get only twelve rows. A manager wanted a total for each month of each year. What is wrong, and how do you fix the query so the rows come out in time order?
Show answer
Grouping by CALENDAR_MONTH alone merges the same month from every year, so there are only twelve groups. Add CALENDAR_YEAR(CloseDate) to both SELECT and GROUP BY, and order by year and then month: SELECT CALENDAR_YEAR(CloseDate) yr, CALENDAR_MONTH(CloseDate) mth, SUM(Amount) total FROM Opportunity WHERE IsWon = true GROUP BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate) ORDER BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate). This returns up to 36 rows, and months without won opportunities are absent.
Exercise
In Apex, you read ar.get('expr0') from a query that selects CALENDAR_YEAR(CloseDate) without an alias. What is the risk, and what type should you cast the value to after you add the alias yr?
Show answer
The name expr0 depends on the position of the field in the select list, so reordering the fields silently changes what the code reads. Adding the alias yr makes the key stable and readable. The value is an integer year, so cast it with (Integer) ar.get('yr').