Preface: this post is part of the SOQL: A Beginner’s Guide series.
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. We’ll cover this type of traversal in this post.
As a refresher, upwards traversal is the exact opposite. If you’re querying contacts, upwards traversal could pull data from the contact’s account.
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:
SELECT Id, Name, Account.Description, CreatedBy.Name,(SELECT Amount FROM Opportunities WHERE Amount > 100),FROM Contact WHERE Account.Secret_Notes__c LIKE '%Tacos%' AND (Sex__c = 'Male' OR Likes_Ice_Cream__c = true)
(SELECT Name FROM Best_Friends__r WHERE Phone != null)
This is a ridiculous query and I’m not even gonna try explaining it. Just know that you can query for some crazy things using SOQL!