Skip to main content

GROUP BY

For more details check Check SOQL API - GROUP BY.

NOTE! 🚨 All examples use inline queries built with the SOQL Lib Query Builder. If you are using a selector, replace SOQL.of(...) with YourSelectorName.query().

Group of records instead of processing many individual records.

GROUP BY​

Field​

SOQL

SELECT LeadSource
FROM Lead
GROUP BY LeadSource

SOQL Lib

SOQL.of(Lead.SObjectType)
.with(Lead.LeadSource)
.groupBy(Lead.LeadSource)
.toAggregated();

SOQL

SELECT COUNT(Name) count
FROM OpportunityLineItem
GROUP BY OpportunityLineItem.Opportunity.Account.Id

SOQL Lib

SOQL.of(OpportunityLineItem.SObjectType)
.count(OpportunityLineItem.Name, 'count')
.groupBy('OpportunityLineItem.Opportunity.Account', Account.Id)
.toAggregated();

GROUP BY ROLLUP​

Field​

SOQL

SELECT COUNT(Name) cnt
FROM Lead
GROUP BY ROLLUP(ConvertedOpportunity.StageName)

SOQL Lib

SOQL.of(Lead.SObjectType)
.count(Lead.Name, 'cnt')
.groupByRollup('ConvertedOpportunity', Opportunity.StageName)
.toAggregated();

SOQL

SELECT Type
FROM Account
GROUP BY ROLLUP(Type)

SOQL Lib

SOQL.of(Account.SObjectType)
.with(Account.Type)
.groupByCube(Account.Type)
.toAggregated();

GROUP BY CUBE​

Field​

SOQL

SELECT Type
FROM Account
GROUP BY CUBE(Type)

SOQL Lib

SOQL.of(Account.SObjectType)
.with(Account.Type)
.groupByCube(Account.Type)
.toAggregated();

SOQL

SELECT COUNT(Name) cnt
FROM Lead
GROUP BY CUBE(ConvertedOpportunity.StageName)

SOQL Lib

SOQL.of(Lead.SObjectType)
.count(Lead.Name, 'cnt')
.groupByCube('ConvertedOpportunity', Opportunity.StageName)
.toAggregated();