ForceChallenges
ProblemsDailyNotesInterview
Sign in

Practice

All problemsSOQL practiceApex trigger challengesDaily challengeOpportunityTrigger.oldMapBefore UpdateBulkificationContactValidationGROUP BYSemi-JoinAccountBefore Insert

Interview questions

All questionsAdminAdministrationApexApex TriggerAsync ApexDevelopmentField ServiceField ServiceIntegrationLwc

By company

DeloitteSalesforceAccentureInfosysPwCCognizant

Learn

Study notes

ForceChallenges

AboutContact usPrivacy PolicyTerms of ServiceFor AI assistants (llms.txt)
© 2026 ForceChallenges · Salesforce SOQL & Apex trigger practice
Apex questions22 of 41
ApexMedium 2 min read

When should you choose Database.getQueryLocator() over an iterable in Batch Apex?

Answer

Basics: Batch Apex start() must return either a QueryLocator or an Iterable. A QueryLocator is a server-side cursor: Salesforce holds the query and feeds chunks to execute(), so your code never loads the whole set into memory.

How it works:

  1. start() returns Database.getQueryLocator('SELECT ...').
  2. The platform opens the cursor and slices the results into scopes (default 200).
  3. Each scope runs in its own execute() transaction with fresh limits.
  4. finish() runs at the end.

Advanced / deep dive: With a QueryLocator the total rows retrieved are not counted against the 50,000 row limit (the 50 million cap applies). With an Iterable, start() is an ordinary transaction, so the 50,000 SOQL row limit and heap limits apply to whatever you build there. Limitations of QueryLocator: no aggregate queries (GROUP BY), the query must be a SOQL SObject query, and you cannot combine data from callouts or computed collections. Use Database.getQueryLocatorWithBinds for safe, explicit bind variables rather than string concatenation (injection risk). If you need filtering that SOQL cannot express, prefer to filter in execute() rather than switch to an Iterable.

Code / config example:

apex
public class OldCaseCloser implements Database.Batchable<SObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        Map<String,Object> binds = new Map<String,Object>{
            'cutoff' => Date.today().addDays(-90)
        };
        return Database.getQueryLocatorWithBinds(
            'SELECT Id, Status FROM Case WHERE CreatedDate < :cutoff AND IsClosed = false',
            binds, AccessLevel.USER_MODE);
    }
    public void execute(Database.BatchableContext bc, List<Case> scope) {
        for (Case c : scope) { c.Status = 'Closed'; }
        update scope;
    }
    public void finish(Database.BatchableContext bc) {}
}

Hidden gotchas & must-remember points:

  • 50 million records for QueryLocator; 50,000 for rows queried in an Iterable start().
  • Aggregate queries fail with a QueryLocator.
  • Records are queried at start, but execute() receives the data as it was when the cursor read it; concurrent edits can make it stale.
  • Add selective filters and indexed fields to avoid query timeouts on huge tables.
  • Default scope is 200, max 2000.
  • Dynamic strings need String.escapeSingleQuotes or bind variables.

Best practice: Default to QueryLocator; reach for an Iterable only when the source is not SOQL.

ApexAsynchronous ApexBatch Apex
Practice SOQL & Apex
PreviousHow and why would you use System.abortJob() in asynchronous Apex management?Next How does the Iterable interface work in Batch Apex for custom data collections?

More Apex questions

  • How do you pass runtime parameters into a Batch Apex class prior to execution?
  • What are the primary differences in governor limits between synchronous transactions and asynchronous Apex executions?
  • How do you prevent recursive asynchronous job enqueuing triggered by recursive database DML updates?
  • How can you trigger subsequent asynchronous jobs inside the finish method of a Batch Apex class?
  • How can you track the execution identifier returned when enqueueing a Queueable Apex job?