I have a custom object Contract__c, which is in a relationship with Address__c. A Contract can have many Addresses, so Adress__c has a lookup field to Contract__c.

I am trying to query all the Addresses related to a contract, but I seem to be having difficulties:

SELECT Id, (SELECT Id FROM Address__c) FROM Contract__c

What am I doing wrong here?


You need to go by the relationship which is likely:

SELECT Id, (SELECT Id FROM Address__r) FROM Contract__c

In order to find the correct relationship name you can look here: How to find out relationships for SOQL queries?

EDIT: Expand your project and its on the bottom of Eclipse.

enter image description here

| improve this answer | |
  • Ah, I just realised why it doesn't work It is because Address_c is a junction object. Does that make a difference? I tried appending __r, and it didn't work. – Lily Dec 10 '14 at 22:06
  • It's not necessarily just __r. You'll need to review the lookup field for the relationship name. In addition, based on which 'direction' you you plan to query, the Parent w/ Child query and the Children w/ Parent queries are written significantly different. THIS is your friend salesforce.com/us/developer/docs/dbcom_soql_sosl/Content/… – HomerJ Dec 10 '14 at 22:25
  • Thanks for that link! I have installed the Eclipse IDE, but can't quite find out how to access this schema thingy. How can I open it? – Lily Dec 10 '14 at 23:17
  • @Lily Edited with a screenshot showing where the schema is. – dphil Dec 11 '14 at 14:45

In Relationship Queries For parent-to-child relationships, the parent object has a name for the child relationship that is unique to the parent, the plural of the child object name.

In your case, the query should be:

SELECT Id, (SELECT Id FROM Addresses__r) FROM Contract__c

Let me know whether it works.

| improve this answer | |

Address__r is the relationship name of the Address__c to Contract__c

newAddress is holding all the value of Address__c from trigger.new, So if you have a list of Address then you can use that List of Address instead of newAddress this query will return the Contract related to all Addresses

List<Contract__c> conList = [Select Id,(Select Id from Address__r) from Contract__c where Id IN (Select Address__c from Address__c where Id IN :newAddress)];

If you want to query for single address then simply write the condition for the address in where Clause like:

List<Contract__c> conList = [Select Id,(Select Id from Address__r) from Contract__c where Id IN (Select Address__c from Address__c where Id = '0092813000vzvu1')];
| improve this answer | |

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.