Salesforce provides a powerful querying language known as SOQL (Salesforce Object Query Language) to retrieve data stored within the platform. One common use case is fetching data from a parent object and its related child records. For instance, you might want to retrieve all Accounts and their associated Opportunities. In this blog post, we’ll walk you through how to achieve this using SOQL in Apex.
Understanding the Relationship
Before diving into the code, it’s essential to understand the relationship between the Account
and Opportunity
objects:
- Account: The parent object in this scenario.
- Opportunity: The child object, with a lookup relationship to Account.
Each Opportunity is related to an Account via the AccountId
field, forming a one-to-many relationship where an Account can have multiple Opportunities.
Step 1: Basic SOQL Query for Parent Object
Let’s start by writing a simple SOQL query to retrieve data from the Account
object:
List accounts = [SELECT Id, Name FROM Account];
This query fetches the Id
and Name
fields of all Account
records.
Step 2: Retrieving Child Records Using a Subquery
To retrieve the related Opportunity
records for each Account
, you can use a nested SOQL query. This is known as a parent-to-child query. The syntax involves using a subquery that fetches child records and is enclosed in parentheses.
List accountsWithOpps = [SELECT Id, Name, (SELECT Id, Name FROM Opportunities) FROM Account];
In this query:
(SELECT Id, Name FROM Opportunities)
is the subquery that fetchesOpportunity
records related to eachAccount
.Opportunities
is the relationship name that represents the child relationship fromAccount
toOpportunity
.
Step 3: Understanding the Query Results
The query returns a list of Account
records, and each Account
record contains a list of related Opportunity
records. You can access these child records using Apex code:
for (Account acc : accountsWithOpps) {
System.debug(‘Account Name: ‘ + acc.Name);
for (Opportunity opp : acc.Opportunities) {
System.debug(‘Opportunity Name: ‘ + opp.Name);
}
}
In this loop:
You can then iterate over this list to access each Opportunity
record.
acc.Opportunities
gives you the list of Opportunity
records associated with each Account
.
Using SOQL in Apex to perform parent-to-child queries allows you to efficiently retrieve and process related records in Salesforce.
Watch Bellow Video: