function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chris Feldhacker IIChris Feldhacker II 

Empty QueryLocator?

What is the best way to return a QueryLocator object that returns 0 records?
I have a Batch class that normally need to return >50K records, so I'm using the start() method that returns a QueryLocator.  However, if certain preconditions are not met, then the Batch class should not process any records -- i.e., I want the start method to return an empty result.
Options (that don't work):
1) Having start return null doesn't work as Apex throws an UnexpectedException.
2) Database.getQueryLocator(new List<SObject>()) doesn't work, as Apex requires the parameter to be a SOQL query.
3) Constructing a Database.QueryLocator object directly seems impossible.
Options (that work):
4) Execute Database.getQueryLocator() with a "bogus" SOQL query that is guaranteed to return 0 results (like, WHERE lastmodified date is in the future or some non-nullable field is null).
5) Other ideas?
Chris Feldhacker IIChris Feldhacker II
Forgot to mention:  I also tried System.abortJob(), but it appears aborting a job is done asynchronously.  With the code:
  1. System.debug('TestBatch.start - committing suicide');
  2. System.abortJob(context.getJobId());
  3. System.debug('TestBatch.start - failed');
Line 3 is still executed even though the job is (supposed to be) aborted.
MagulanDuraipandianMagulanDuraipandian
Hi,
1. Use SELECT Id FROM Account WHERE Id = null so that the result will be zero instead of returning null.
or
2. Create a schedulable class, do the precondition in it  and then call the batch class from the schedulable class.
--
Magulan Duraipandian
www.infallibletechie.com
Chris Feldhacker IIChris Feldhacker II
I realized there's an even more obvious solution to ensuring an empty result: 
SELECT Id FROM Account LIMIT 0
Works like a charm!