Loading

Apex CPU time limit exceeded due to complex SOQL queries in a batch start method in Salesforce

Data pubblicazione: Aug 18, 2026
Descrizione

When executing SOQL queries from Apex, operations that don't consume application server CPU time aren't counted towards the Apex CPU time limit calculation. See the Maximum CPU time details under Per-Transaction Apex Limits.

Cause

SOQL queries can make a significant contribution to the application server Apex CPU time limit based on the volume of related or sub-query data being retrieved while starting a batch job in Salesforce.

Example Problematic Queries

The following are examples of SOQL queries with complex relationships that, when combined with a large volume of data for a batch job, can significantly impact the Apex CPU limit and cause it to be exceeded.

This first example queries several related child objects' fields directly in the start method, across multiple relationship filters:

SELECT
child1__r.Id, child1__r.Name,
child2__r.Id, child2__r.Name, child2__r.Status__c,
child2__r.abc__c, child2__r.xyz__c, child2__r.Date__c,
child2__r.CurrencyIsoCode, child2__r.text__c, child2__r.Birthdate__c,
child3__r.Id, child3__r.Name, child3__r.Status__c, child3__r.Date__c,
child3__r.CurrencyIsoCode, child3__r.text__c
FROM Parent__c
WHERE
Createddate >= date OR child1__r.createdate > date OR child2__r.createdate > date

This second example uses a sub-query (child relationship query) inside the start method, which similarly adds cost across the batch's related records:

SELECT
id, Name,
(SELECT child1__r.Id, child1__r.Name, child2__r.Id, child2__r.Name, child2__r.Status__c,
child2__r.abc__c, child2__r.xyz__c, child2__r.Date__c From Child)
FROM Parent__c
WHERE
Createddate >= :date OR child1__r.createdate > :date OR child2__r.createdate > :date
Risoluzione

This section explains how to restructure a batch job's start method to avoid exceeding the Apex CPU time limit.

Resolution

If the batch job's start method is encountering an Apex CPU time limit exceeded message due to relationship or sub-query complexity and data volume, distribute that complexity across the batch's execution instead of loading it all in the start method.

Before

Simplify the batch job's start method SOQL query to only find the details of the primary record, rather than including related/child fields:

SELECT Id
FROM Parent__c
WHERE
Createddate >= :date OR child1__r.createdate > :date OR child2__r.createdate > :date

After

Within each batch's execute method, query for only the required related records for the primary records currently being processed in that batch:

SELECT Name, Status__c, Date__c, CurrencyIsoCode, text__c
FROM Child__c
WHERE ParentId in :scope and createdate > :date
Numero articolo Knowledge

002503080

 
Caricamento
Salesforce Help | Article