Difference Between Database.query() and Database.getQueryLocator()

Database.query():

  • Database.query() allows to make a dynamic SOQL query at runtime. It returns a single sObject when the SOQL query returns a single record and it returns a list of sObjects when the SOQL query returns more than a single record.
  • We can retrieve up to 50,000 records using Database.query().
  • In Batch Apex, if we use Database.query(), it supports 50,000 records only.
  • If VF page doesn’t have read only attribute, use .
  • Use Database.query() in Visualforce page, if the readOnly attribute is false.

Database.getQueryLocator():

  • Database.getQueryLocator() returns a Query Locator that runs the selected SOQL query returning list that can be iterated over in batch apex and Visualforce page.
  • We can retrieve up to 10,000 records.
  • We can’t use getQueryLocator with any query that contains an aggregate function.
  • Use Database.getQueryLocator() in Visualforce page, if the readOnly attribute is true.
  • In Batch Apex, Database.getQueryLocator() supports up to 50 million records.
  • We can’t use the FOR UPDATE keywords with a getQueryLocator query to lock a set of records, In batch apex the start method automatically locks the set of records in the batch.