0

I have a requirement, where I need to retrieve Account history while querying Contact object.

Is it possible something like below?

SELECT ID, Account.id, (SELECT field, currentvalue, previousvalue FROM AccountHistory) FROM CONTACT.

2

You can't directly query AccountHistory from a Contact as a parent-child subquery can only be 1 level deep, and there must be a direct relationship from the parent object to the child object.

Instead, to accomplish this, you'll need to gather a collection of Account Ids referenced by the collection of Contacts that you're working with, and either query AccountHistory directly, or query for Accounts and include the parent-child subquery.

An example:

Set<Id> accountIds = new Set<Id>();
for(Contact cont :contacts){
    accountIds.add(cont.AccountId);
}

List<Account> accountsWithHistories = [SELECT Id, (SELECT oldValue, newValue, field FROM AccountHistories) FROM Account WHERE Id IN :accountIds];
  • I was using List<Id> whenever I had to use collection inside SOQL with IN. Nice use of Set<Id>. – karthikselva Feb 9 '16 at 19:34
  • 1
    Yeah, I like having the assurance that there won't be any duplicate Ids (which has caused some dml errors for me in the past) in the collection. It also simplifies checking for and removing/not adding null Ids with someIdSet.remove(null); – Derek F Feb 9 '16 at 19:43
  • It makes perfect sense here. In case if we have knowledge that Id's were unique in different scenario (say SOQL is [Select Id from Account]), would you recommend List<Id> ? coz I assume Set comes with a extra cost of validating and removing dups on every set.add(entry). – karthikselva Feb 9 '16 at 19:50
  • @karthikselvakumar This is starting to get off-topic, and might be a decent question (if it hasn't already been asked). The underlying implementation of Sets are a Java HashMap, which generally has an insertion complexity of O(1). Basically, it's fast, don't worry about any additional overhead, it's practically non-existent. – Derek F Feb 9 '16 at 20:25
  • I found this question in recent list and thought it would be helpful salesforce.stackexchange.com/questions/110320/… – karthikselva Feb 16 '16 at 5:32

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.