my requirement is whenever OpportunityLineItem Created makes the sum of quantity available for Opportunity and also take care of rest of Opportunity for particular Account and update Total Sales Quantity.

Here is the code I'm Coming up with.

**Can Someone suggest any other Linear Way or my Code is fine?**

public class OpportunityLineItemHandler {
    public static void getTotalSalesQuantity(List<OpportunityLineItem> newOpportunityLineItemList){
        Set<Id> ParentOppIdsSet = new Set<Id>();
        for(OpportunityLineItem objOppLine : newOpportunityLineItemList){
        Map<Id,Decimal> NoOfOpportunityQuantity = new Map<Id,Decimal>();
        for(AggregateResult ar : [SELECT OpportunityId,SUM(Quantity)sumOfQuantity FROM OpportunityLineItem GROUP BY OpportunityId ]){
            NoOfOpportunityQuantity.put( (Id)ar.get('OpportunityId') , (Decimal)ar.get('sumOfQuantity') );
        Set<Id> grandParentAccount = new Set<Id>();
        for(Opportunity oppObj : [SELECT Id,AccountId FROM Opportunity WHERE Id IN : ParentOppIdsSet]){
        List<Account> accountsToBeupdated = new List<Account>();
        for(Account objAcc : [SELECT Id, Total_Sales_Quantity__c,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN : grandParentAccount]){
            Decimal totalSalesbyAccountId = 0;
            for(Opportunity objOpp : objAcc.Opportunities){
                    totalSalesbyAccountId = totalSalesbyAccountId + NoOfOpportunityQuantity.get(objOpp.Id);
            objAcc.Total_Sales_Quantity__c = totalSalesbyAccountId;
        update accountsToBeupdated;
  • 1
    why not use RSF field on Account that rolls up Opportunity.Quantity__c that is also an RSF of OpportunityLineItem.Quantity? No code required at all
    – cropredy
    Mar 13, 2022 at 15:33
  • @cropredy I know It can be done by Roll-up summary field but in case I'm having this kind of requirement in the future for Lookup Relationship, That's why I want to know that is a good approach for apex or not.
    – whoisnilu
    Mar 13, 2022 at 15:42
  • 1
    Use DLRS for lookup relationships. Widely used and accepted as best practice
    – cropredy
    Mar 13, 2022 at 15:43
  • @cropredy Thanks for suggesting this wonderful tool!!
    – whoisnilu
    Mar 13, 2022 at 15:53
  • 1
    There's also apex rollup as well now as another option. Mar 13, 2022 at 15:56

1 Answer 1


In your particular use case, the easiest thing to do is:

  • Define a RSF field Opportunity.Quantity__c thats rolls up OpportunityLineItem.Quantity
  • Define a RSF field Account.AllOpportunityQuantity__c that sums Opportunity.Quantity__c

No Apex code involved

Should you have lookup relationships to sum over, use the free open source packages which are widely used:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .