SUBQUERY
For more details check Check SOQL API - SubQuery.
NOTE! 🚨 All examples use inline queries built with the SOQL Lib Query Builder. If you are using a selector, replace
SOQL.of(...)
withYourSelectorName.query()
.
SOQL
SELECT Id, Name, (
SELECT Id, Name FROM Contacts
) FROM Account
SOQL Lib
SOQL.of(Account.SObjectType)
.with(Account.Id, Account.Name)
.with(SOQL.SubQuery.of('Contacts')
.with(Contact.Id, Contact.Name)
)
.toList();
Fields​
SObjectField Fields (Recommended)​
SOQL
SELECT Id, Name, (
SELECT Id, Name FROM Contacts
) FROM Account
SOQL Lib
SOQL.of(Account.SObjectType)
.with(Account.Id, Account.Name)
.with(SOQL.SubQuery.of('Contacts')
.with(Contact.Id, Contact.Name)
)
.toList();
String Fields​
SOQL
SELECT Id, Name, (
SELECT Id, Name FROM Contacts
) FROM Account
SOQL Lib
SOQL.of(Account.SObjectType)
.with(Account.Id, Account.Name)
.with(SOQL.SubQuery.of('Contacts')
.with('Id, Name')
)
.toList();
Parent Fields​
SOQL
SELECT Id, Name, (
SELECT Id, Name, CreatedBy.Id, CreatedBy.Name
FROM Contacts
) FROM Account
SOQL Lib
SOQL.of(Account.SObjectType)
.with(Account.Id, Account.Name)
.with(SOQL.SubQuery.of('Contacts')
.with(Contact.Id, Contact.Name)
.with('CreatedBy', new List<SObjectField>{
User.Id, User.Name
})
)
.toList();
Nested SubQuery​
SOQL supports relationship queries that traverse up to five levels of parent-child records. Query Five Levels of Parent-to-Child Relationships in SOQL Queries.
SOQL
SELECT Id, Name, (
SELECT FirstName, LastName , (
SELECT Id, AssetLevel FROM Assets
) FROM Contacts
) FROM Account
SOQL Lib
SOQL_Account.query()
.with(Account.Id, Account.Name)
.with(SOQL.SubQuery.of('Contacts')
.with(Contact.FirstName, Contact.LastName)
.with(SOQL.SubQuery.of('Assets')
.with(Asset.Id, Asset.AssetLevel)
)
).toList();