Query Five Levels of Parent-to-Child Relationships in SOQL

Query Five Levels of Parent-to-Child Relationships in SOQL

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

The most recent version of SOQL allows relationship queries to traverse up to five levels of parent-child data. This implies that a single SOQL query can be used to retrieve parent-child records from five different levels.

Please be aware, nevertheless, that this capability is limited to doing SOQL queries on both standard and custom objects through REST and SOAP query calls.
The maximum number of Parent-to-Child connection levels for SOQL searches in Salesforce's Apex class is still limited to two.

Relationship queries in SOQL can have a parent root as the first level and go up to four levels deep with child relationships starting with API version 58.0. With this update, developers may now create complex searches that retrieve data from several parent and child items simultaneously. Before this improvement, these kinds of inquiries were to be made as several independent requests, which added to the complexity and might have affected performance.

The form you have selected does not exist.

Watch The Video Or Read The Article (Or Do Both smile)

Data Model

I have created a data model with five level deep by introducing three new custom objects as Third Object, Fourth Object & Fifth Object. Third Object has a lookup relationship with Contact, Fourth Object has a lookup relationship with Third Object & Fifth Object has a lookup relationship with Fourth Object.

Below is the screenshot of the data model.

Let's Write The SOQL Query

I have manually loaded some data into Third, Fourth and Fifth custom object manually. With the data set, the query to fetch all five level data in single SOQL query will look like -

SELECT Id, Name,
 (
 SELECT ID, LastName,
 (
 SELECT Id, 
 (
 SELECT ID, 
 (
 SELECT ID FROM Fifth_Objects__r
 )
 FROM Fourth_Objects__r
 )
 FROM Third_Objects__r
 )
 FROM Contacts
 )
 FROM Account

When I executed the above SOQL query in workbench, here comes the result which fetches data till five level deep. 

Perform Callout

The query to execute the above query in REST API is

/services/data/v58.0/query?q=SELECT+Id,Name,+(SELECT+ID,LastName,+(SELECT+Id,+(SELECT+ID,+(SELECT+ID+FROM+Fifth_Objects__r)+FROM+Fourth_Objects__r)+FROM+Third_Objects__r)+FROM+Contacts)+FROM+Account

And the result came back with five level deep object data fetched.

Best Practices

Although performing five-level parent-to-child relationship queries is incredibly powerful and convenient, there are a few best practices and things to keep in mind:

1. API Version Compatibility: Keep in mind that starting with API version 58.0, you can use the enhanced parent-to-child relationship queries. To take advantage of this feature, you'll need to upgrade your organization if it still uses an outdated version of the API.

2. Data Volume: Take into consideration the amount of data that these queries require. The amount of records that are obtained when navigating through several layers may be substantial, which may affect the query execution time. Examine your data model and make the necessary adjustments to the query depth.

3. Query Optimization: Performance optimization is crucial for any query. To reduce the volume of data returned, carefully review the fields you retrieve and apply selective filters. This method lowers the chance of exceeding governor limits while ensuring effective execution.

4. Query Complexity: Although the enhanced features make retrieving complicated data easier, the resulting queries may become more complex. Make sure your query logic is still comprehensible and manageable. If necessary, think about dividing up complicated searches into smaller, easier-to-manage chunks.

Final Thought

With REST and SOAP calls, parent-child data up to five layers deep can be efficiently retrieved in a single query according to the most recent SOQL upgrade. Nevertheless, the Apex class still has a two-level Parent-to-Child connection constraint, therefore this feature is limited to those calls.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments

Evaluate Dynamic Formulas In Apex

Evaluate Dynamic Formulas In Apex

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

What is Evaluate Dynamic Formulas in Apex?

"Evaluate Dynamic Formulas in Apex" is a new feature in Salesforce scheduled for release with Summer '24 (currently in beta). It allows developers to programmatically evaluate Salesforce formulas within Apex code. This means you can write code that takes a formula as input (as a string) and evaluates it based on the context you provide, similar to how formulas are evaluated in fields or rules within Salesforce.

Here are some potential benefits of this feature:

  • Real-time Calculations: Eliminate the need to store pre-calculated formula results in fields, improving efficiency.
  • Increased Flexibility: Create more dynamic logic in automations, validations, and workflows by evaluating formulas at runtime.
  • Enhanced User Experience: Build custom formula editors that leverage the power of the Salesforce formula engine.

The form you have selected does not exist.

Watch The Video Or Read The Article (Or Do Both smile)

Example Code:

Below is one sample code using Apex Cursors

public with sharing class DynamicFormula {
 public void opportunityChecker(String opportunityId){
 Opportunity singleOpp = [Select Id, Amount, ExpectedRevenue, Probability from Opportunity where Id =: opportunityId LIMIT 1];
 String formulaExpresssion = '(Amount > 10000 && Probability > 50) || (ExpectedRevenue > 20000 && Probability > 80)';
 FormulaEval.FormulaBuilder likelyConvertOpportunity = Formula.builder()
 .withType(Opportunity.SObjectType)
 .withReturnType(FormulaEval.FormulaReturnType.BOOLEAN)
 .withFormula(formulaExpresssion); 
 FormulaEval.FormulaInstance instance=likelyConvertOpportunity.build();
 Boolean formulaOutcome = (Boolean)instance.evaluate(singleOpp);
 System.Debug('Formula Result: ' + formulaOutcome);
 }
}

Explanation Of The Code

To create an instance of the formula, I have called the static method builder() in the FormulaBuilder class and passed in the context object, return type, and formula text in the code above. The formula instance was validated by calling the build() function. In the event that the validation fails, the build() method generates the FormulaValidationException exception.

To calculate the formula expression and return the result, I have used the evaluate() function of the FormulaInstance class. If the evaluation yields an error, the method generates the FormulaEvaluationException exception.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments

Improve SOQL Performance By Using Apex Cursors

Improve SOQL Performance By Using Apex Cursors

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

What is Apex Cursor?

Apex Cursors are a new beta feature in Salesforce Summer '24 release that allows you to work with large datasets retrieved using SOQL queries. Unlike SOQL which returns the entire dataset at once, Cursors retrieve data in manageable chunks, improving performance and memory usage.

Cursors provide some advantages over Batch Apex, such as:

  • Forward and backward navigation within the results.
  • Ability to be chained in a series of queueable Apex jobs.

Cursor processing occurs within a single transaction, ensuring data consistency. Cursors are an alternative to batch Apex and address some of batch Apex’s limitations. Cursors are also more powerful because they can be used in a chain of queueable Apex jobs.

The form you have selected does not exist.

Watch The Video Or Read The Article (Or Do Both smile)

Apex Cursors Are Improving SOQL Query Performance

The benefit of Apex Cursors lies in how they handle the results of large SOQL queries. Here's how they improve performance in that aspect:

Reduced Memory Usage: Large SOQL queries can return massive datasets that overload memory. Cursors fetch data in smaller batches, reducing the amount of data loaded into memory at once. This frees up resources and improves overall system performance.

Faster Processing: By processing data in manageable chunks, Apex Cursors can iterate through large datasets quicker compared to loading everything at once. This translates to faster execution times for your Apex code that utilizes cursors.

Improved Scalability: Apex Cursors allow you to handle even larger datasets efficiently. This makes your code more scalable as your data volume grows.

Transaction Boundaries: Cursors always operate within a single transactions. This means developers can write Apex cursors to process large amount of data without worrting about exceeding transaction limits.

Forward and Backyard Navigation: Developers can move forward and backyard through the data set which brings the flexibility to manipulate data effectively.

In simpler terms, Apex Cursors act like a pacer for your SOQL queries. They ensure you're not overwhelmed by a massive dataset at once, leading to smoother and faster processing of large amounts of data retrieved through SOQL.

Things To Know About Apex Cursors

Apex Cursor Creation: A cursor is created when a SOQL query is executed on a Database.getCursor() or Database.getCursorWithBinds() call. 

Fetch Records Using Apex Cursor: When a Cursor.fetch(integer position, integer count)method is invoked with an offset position and the count of records to fetch, the corresponding rows are returned from the cursor. The maximum number of rows per cursor is 50 million, regardless of the operation being synchronous or asynchronous.

Get Number Of Cursor Rows: To get the number of cursor rows returned from the SOQL query, use Cursor.getNumRecords().

Understand The Limits: Apex cursors have the same expiration limits as API Query cursors. To get Apex cursor limits, use these new methods in the Limits class.

  • Limits.getApexCursorRows() and its upper bound Limits.getLimitApexCursorRows() method
  • Limits.getFetchCallsOnApexCursor() and its upper bound Limits.getLimitFetchCallsOnApexCursor() method

Understand Exceptions: Apex cursors throw these new System exceptions: System.FatalCursorExceptionandSystem.TransientCursorException. Transactions that fail withSystem.TransientCursorExceptioncan be retried.

Remember Apex Cursor Limits

  • Maximum number of rows per cursor: 50 million (both synchronous and asynchronous)
  • Maximum number of fetch calls per transaction: 10 (both synchronous and asynchronous) 
  • Maximum number of cursors per day: 10,000 (both synchronous and asynchronous)
  • Maximum number of rows per day (aggregate limit): 100 million

Example Code:

Below is one sample code using Apex Cursors

public class QueryChunkingQueuable implements Queueable {
 private Database.Cursor locator;
 private integer position;
 public QueryChunkingQueuable() {
 locator = Database.getCursor
 ('SELECT Id FROM Contact WHERE LastActivityDate = LAST_N_DAYS:400');
 position = 0;
 }
 public void execute(QueueableContext ctx) {
 List<Contact> scope = locator.fetch(position, 200);
 position += scope.size();
 // Perform the Business Logic
 if(position < locator.getNumRecords() ) {
 // Process the next chunk
 System.enqueueJob(this);
 }
 }
}

Explanation Of The Code

  • Database.getCursor() method will create the instance of QueryChunkingQueuable. This method needs a query. In this case, the query is to fetch all contacts where the LastActivityDate falls withing last 400 days.
  • Within the execute() method, first we fetch 200 contacts at a time usineg locator.fetch( position, count ) method.
  • position is kind of the pointer which keep track of the current posotion to process data incrementally.
  • We check if there is any more data left i.e. more than 200, we then enequeue another job to continue processing rest of the records.

Difference Between Apex Curors And Batch Apex

  • With cursors, we can move backyard and forward which brings lot of flexibility. Whereas with batch, we can only move forward.
  • Cursors can seamlessly work on a chain of queueable jobs for complex data processing. Whereas batch job works typecally as a standalone job and chaining is very complex.

Final Thought

Overall, Apex Cursors empower you to:

    • Handle even larger datasets efficiently.
    • Improve the performance of your Apex code when dealing with big data.
    • Scale your applications more effectively as your data volume grows.

This makes them ideal for scenarios like:

    • Mass data updates.
    • Complex data transformations on large datasets.
    • Iterating through large customer lists or opportunity records.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments

How To Switch To Lightning Threading

How To Switch To Lightning Threading

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

What is Email Threading?

Email threading in Salesforce refers to the process of automatically grouping related emails together in the context of a specific record, typically a case. This way, you can see the entire conversation history between a customer and your support team in one place.

Salesforce offers a few different methods for achieving email threading:

  • Lightning Threading (available since Spring '23): This is the newest approach and relies on secure tokens embedded in outgoing emails. When a customer replies to an email with a token, Salesforce can match it back to the relevant case.

  • Email Header-Based Threading: This method looks for a specific email header field (Message-ID) in the "In-Reply-To" and "References" fields to link replies to the original email.
  • Ref ID-Based Threading (mostly replaced by Lightning Threading): In this older method, a reference ID was included in the email subject line to associate replies with a particular case.

Lightning threading is generally considered the most secure and reliable option, as it avoids potential issues with customers modifying the subject line and removing the Ref ID.

The form you have selected does not exist.

What is The Reason For This Change?

Emails can be securely threaded using lightning threading, which links incoming and outgoing emails to relevant cases. Email-to-Case detects corresponding cases more reliably and avoids producing a new case when a similar case already exists because Lightning threading mixes token- and header-based threading.

How is This Lightning Threading Different?

Email-to-Case in Lightning threading adds a token to the subject or content of an outgoing email on a case. Tokens are uniquely formed strings, much like Ref IDs, but they are generated in a fashion that complies with Salesforce security requirements. Email-to-Case searches for tokens in a customer's answer to an outgoing case email in order to match the incoming message to the relevant case. Email-to-Case then reverts to header-based threading and looks for a Message-ID in the In-Reply-To and References headers if no match is found. Email-to-Case generates a new case in the event that token- and header-based threading combined are unable to find a matching case.

Email-to-Case stops inserting a Ref ID in outgoing emails and stops using Ref IDs in incoming emails for matching when you switch to Lightning threading.

When is This Change Coming To My Org?

This update was first available in Winter ’21 and is enforced in Summer ’22. This update was originally scheduled to be enforced in Winter ’22 but was postponed.

How To Enable This?

To review this update, from Setup, in the Quick Find box, enter Release Updates, and then select Release Updates. For Disable Ref ID and Transition to New Email Threading Behavior. View the update’s details and then click Enable Test Run to enable the header-based threading update.

What is The Expected Behavior?

  • Salesforce will set email preferences for threading tokens based on the corresponding Ref ID settings for email subjects and bodies as they are currently enabled. 
  • Incoming emails are matched to cases using tokens rather than Ref IDs in the email subject or body. If no matching case is found, email header-based threading is used. Outgoing emails no longer contain a Ref ID. 
  • You need to change your custom code like -
    • The Apex method getCaseIdFromEmailThreadId was deprecated. For incoming emails, include the EmailMessages.getRecordIdFromEmail or Cases.getCaseIdFromEmailHeaders methods to retrieve case identifiers from email tokens or email headers, respectively.
    • For outgoing emails, use the EmailMessages.getFormattedThreadingToken or Cases.generateThreadingMessageId methods to include a threading token or email header-based threading information, respectively, in outbound emails. Email-to-Case can then thread replies to the right cases.
  • Existing cases and emails will continue to thread using header-based. threading. No extra action is needed.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments