Using Batch Apex with non-dynamic (static) SOQL

If you look at the Using Batch Apex guide in the developer docs, all of the examples use Dynamic SOQL, that is SOQL that can be constructed using a String, as in

List<Account> accounts = Database.query('select id from account limit 10');

in contrast to non-dynamic soql or static soql, as in

List<Account> accounts = [select id from account limit 10];

The start() method of batch apex either returns a Database.QueryLocator or a Iterable<sObject>. In the examples that return a Database.QueryLocator, the examples all create it via

return Database.getQueryLocator(query);

If you want to use non-dynamic soql, for example if you want to take advantage of the out of the box binding Apex variables, then you’ll need a way to convert from [ ] to a String. It’s sort of hidden in another part of the developer docs, but I was able to find an API reference of sorts for Database.QueryLocator. The way to run the start method for non-dynamic soql would be by following this pattern:

return Database.getQueryLocator([select id from account]);

It should be noted that if [select id from account] returns more than the max number of rows (currently 10,000), that this will NOT throw a Governor Limit Exception.

This entry was tagged , , . Bookmark the permalink.