0

Currently, I have a custom object of the name University and have a lookup field to another custom object of the name School Details.

I want to query fields of School Details object. How would I do that?

This is what I have (not correct)

Select Id, Name, (Select Name From School_Details__c) From University__c
0

2 Answers 2

2

Downwards traversal is when you’re pulling records from a related list. For example, if we’re doing a SOQL query on accounts, downwards traversal could pull data from the account’s contacts.

Let’s take a look at a downwards traversal SOQL query:

SELECT Id, Name, Industry, AnnualRevenue,( SELECT Name, Email, BirthDate FROM Contacts ) FROM Account

We essentially have two queries in one SOQL statement. One to pull the general account data, and one to pull the contact related list.

Don’t forget these three things when using downwards traversal:

  1. The nested query is treated like another field. That’s why there is a comma after the AnnualRevenue field.
  2. We use the plural version “Contacts” in the nested SOQL query. If you need to find the keyword for a custom relationship, find the lookup or master-detail field and look here:

    enter code here

  3. You can combine all the SOQL techniques you’ve learned into your query!

    SELECT Id, Name, Account.Description, CreatedBy.Name, (SELECT Amount FROM Opportunities WHERE Amount > 100), (SELECT Name FROM Best_Friends__r WHERE Phone != null) FROM Contact WHERE Account.Secret_Notes__c LIKE '%Tacos%' AND (Sex__c = 'Male' OR Likes_Ice_Cream__c = true)
    

Reference:- How to write a cross-object SOQL query (“downwards”)

1

for the custom object you have to define "__r" to get child record.

"__r" is used for retrieving field values from the object's related another object when those objects have relationship via Lookup field.

see link below for detail and sample:

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_and_custom_objects.htm

Updated query will be"

Select Id, Name, (Select Name From School_Details__r) From University__c
2
  • 1
    This answer is a tad on the short side. Ideally, an answer like this would also reference documentation, and go over what School_Details__r in the query is/why __r is used here (like Sanket Kumar does in his answer).
    – Derek F
    Commented Aug 21, 2018 at 13:19
  • @DerekF Thanks or the suggestion. I have updated the description as well as reference link :) Commented Aug 21, 2018 at 15:11

Not the answer you're looking for? Browse other questions tagged .