DML on Cross Object Data

 Below is the pseudo-code to show that the same logic can be written in multiple ways.

Approach 1:

// Query for contact info
List < Contact > cts = [SELECT ID, AccountID from Contact
    where Location__c = 'USA'
    CreatedDate = Last_N_Days: 10
];

// Get list of account IDs.
Set < ID > accountIds = new Set < ID > ();
for (Contact ct: cts) {
    if (ct.AccountID != null) {
        accountIds.add(ct.AccountID);
    }
}

if (accountIds.size() > 0) {
    List < Account > accounts = [Select ID, AnnualRevenue from Account where ID in: accountIds];
    for (Account accountFound: accounts) {
        if (accountFound.AnnualRevenue == null)
            accountFound.AnnualRevenue = 500;
    }

    update accounts;
}

Approach 2: The above code is refactored by reducing the SOQL count 

// Query for contact info and annual revenue on account in a single query
List < Contact > conList = [SELECT ID, AccountID, Account.ID,
    Account.AnnualRevenue from Contact
    where Location__c = 'USA'
    AND CreatedDate = Last_N_Days: 10 AND AccountId != null AND Account.AnnualRevenue == null
];

// Some code that take data by navigating from Contact and update in Account. 
Map < ID, Account > accountsToUpdate = new Map < ID, Account > ();
for (Contact con: conList) {
    if (!accountsToUpdate.containsKey(con.AccountID)) {
        con.Account.AnnualRevenue = 500;
        accountsToUpdate.put(con.AccountID, con.Account);
    }
}
if (accountsToUpdate.size() > 0) {
    update accountsToUpdate.values();
}

Approach 3:
List<Account> lstAccount = [SELECT Id, AnnualRevenue FROM Account WHERE AnnualRevenue = Null AND Id IN
                            (SELECT AccountId FROM Contact WHERE Location__c = 'USA' AND CreatedDate = Last_N_Days: 10)];
if(lstAccount.size() > 0)
{                   
    for(Account acc : lstAccount)
    {
        acc.AnnualRevenue = 500;
    }
    update lstAccount;
}

Note: To check How many SOQL queries consumed you can use the LIMITS class as shown below:
System.debug('--Limits'+Limits.getLimitAggregateQueries()); // 300
System.debug('--Limits'+Limits.getLimitQueries()); //100
System.debug('--Limits of agg '+Limits.getAggregateQueries()); // 0
System.debug('--Limits of Queries '+Limits.getQueries()); // 0

List<Account> lstAccount = [SELECT Id, AnnualRevenue FROM Account WHERE Id IN
                            (SELECT AccountId FROM Contact )];

System.debug('--After Limits'+Limits.getLimitAggregateQueries()); //300
System.debug('--After Limits'+Limits.getLimitQueries()); // 99
System.debug('--After Limits of agg '+Limits.getAggregateQueries()); //0
System.debug('--After Limits of Queries '+Limits.getQueries()); // 1

Comments

Post a Comment