3

Is there any way the below code can be simplified into a single query?:

List<Contract> contractsToUpdate = new List<Contract>();

        for (Contract cont: [SELECT AccountId, OwnerId, Account.OwnerId FROM Contract WHERE Account.Type != 'Wholesale partner']) {
            if (cont.OwnerId != cont.Account.OwnerId) {
                cont.OwnerId = cont.Account.OwnerId;
                contractsToUpdate.add(cont);
            }
        }

My approach:

for (Contract cont: [SELECT AccountId, OwnerId, Account.OwnerId FROM Contract WHERE Account.Type != 'Wholesale partner' AND OwnerId != Account.OwnerId]) {
                cont.OwnerId = cont.Account.OwnerId;
                contractsToUpdate.add(cont);
            }

But OwnerId != Account.OwnerId is not allowed in SOQL hence my approach is not valid

5

Note that you are not using two queries above, but rather one query to get your "outer contracts", and then one more query per. If you have 100 "outer contracts" you'll consume your governor limit and get a LimitsException.

No, you can't do what you want in one query. However, you can add a checkbox formula that will tell you what you need to know, then query on that.

Formula

OwnerId = Account.OwnerId

Query

WHERE Is_Owned_By_Account_Owner__c = false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.