Instead of writing two separate query and execute two separate time, I'm thinking if I can combine into one.

Here is my first query:

SELECT Has_Attachment__c,Id,Name, profile__c FROM profile__c

the second query:

SELECT Id,Name,ParentId FROM Attachment WHERE parentid = 'XXXXXXXXXXXX'
  • Can you please edit your post to clarify the relationships? What type of object is the Profile__c lookup to? Are you looking for Attachment records under the same parent? Is it a required lookup? – Adrian Larson May 18 '16 at 20:01
  • looking for Attachment records under the same parent – Nick Kahn May 18 '16 at 20:03
  • parent to child relationship is a master/detail – Nick Kahn May 18 '16 at 20:08
  • But what type of object does Profile__c refer to? – Adrian Larson May 18 '16 at 20:09
  • You need to provide the objects relationships or is not going to be easy to let you know how to build your query. You can also take a look to this page: developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… for extra information on how to build your SOQL and SOSL queries. – Carlos Naranjo May 18 '16 at 20:09

Let's say that your Profile__c field is a reference to an object called Parent__c. The first step is to find the corresponding ChildRelationship (documentation). Execute Anonymous to the rescue:

for (ChildRelationship relationship : SObjectType.Parent__c.getChildRelationships())
    if (relationship.getChildSObject() == Comp_Profile__c.sObjectType)
        system.debug(relationship.getRelationshipName()); // you need this in SOQL

Cool, so now you now the API Name to use in your subquery. It should look like Comp_Profiles__r or something like that. You can run the same process for Attachment and find that the relationship name is Attachments. Now, you need to do a subquery on the Parent__c object.

    (SELECT Name FROM Attachments),
    (SELECT Name, Has_Attachment__c FROM Comp_Profiles__r)

One SOQL Query can Address only one Object. Unless if you want to access the Parent Data. That is Limitation on SOQL. If there is relation between these 2 objects you can. If you use SOSL you can address multiple objects.

  • 3
    This answer is factually incorrect. You can query parent and child data via SOQL, as long as there is a relationship. – Adrian Larson May 18 '16 at 20:06
  • @AdrianLarson The English in this post seems to be second language and not perfect but it seems Siva is indicating the ability to query through the parent/child relationship. ` Unless if you want to access the Parent Data` – dBeltowski May 18 '16 at 20:53
  • 1
    @DougB It has been updated. Check the edit history, the initial answer indicated it was not possible. – Adrian Larson May 18 '16 at 20:59

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.