Development questions
Write a SOQL query to find all Contacts where the Contact's OwnerId is different from its Parent Account's OwnerId (Explain why SOQL cannot directly compare two fields like WHERE OwnerId != Account.OwnerId and how to solve it via a Formula checkbox field).
SOQL cannot compare two fields in a WHERE clause (e.g. WHERE OwnerId != Account.OwnerId is invalid); filters compare a field with a literal or bind variable only.
Solutions:
- Create a formula checkbox on Contact, e.g.
Owner_Differs__c = OwnerId <> Account.OwnerId, then queryWHERE Owner_Differs__c = true. Formula fields aren't indexed, so it may be non-selective on large data. - Query both fields and compare in Apex:
apex
for (Contact c : [SELECT Id, OwnerId, Account.OwnerId FROM Contact WHERE AccountId != null]) {
if (c.OwnerId != c.Account.OwnerId) { /* mismatch */ }
}
soqlscenariolimitationsformula-fields
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?