+ Start a Discussion
Chidanand MChidanand M 

Difference between Database.query() and database.getQueryLocator()

Hai folks,

Could u plz tell me the exact difference between Database.query() and Database.getQueryLocator(). When and in which situation v need to make use of respective methods. TIA
Himanshu ParasharHimanshu Parashar
Hi Chidu,

database.query allows you to make a dynamic SOQL query at runtime. You can build up a string and then use that as a query string at run time in the database.query statement to make a SOQL call that is determined at run time.

 
database.getQueryLocator returns a Query Locator that runs your selected SOQL query returning list that can be iterated over in bathc apex or used for displaying large sets in VF (allowing things such as pagination). 

 
The query locator can return upto 50 million records and should be used in instances where you want to bactha a high volume of data up (pagination or batch apex). The database.query method should be used in instances where you are wanting to do a dynamic runtime SOQL query for your code.

Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
KaranrajKaranraj
Database.Query() - It will allows you build a dynamic query at runtime. Example - You build a dynamic query and keep it in string variable and use that string variable in the database.query
String fieldName = 'Name,Phone';
String dynQuery = 'select Id ' + fieldName + ' From Account';
Database.query(dynQuery);
Database.Querylocator() - It returns a Query Locator of your soql query. The query result can be iterated over in batch apex or you can also use it visualforce page to display records. The query locator can return upto 50 million records.

Thanks,
karanrajs.com


 
Arun ChaubeyArun Chaubey
Hi Chidu,


database.query allows you to make a dynamic SOQL query at runtime. You can build up a string and then use that as a query string at run time in the database.query statement to make a SOQL call that is determined at run time.

database.getQueryLocator returns a Query Locator that runs your selected SOQL query returning list that can be iterated over in bathc apex or used for displaying large sets in VF (allowing things such as pagination).

Database.queryLocator http://goo.gl/9XK8AS
Database.queryhttp://goo.gl/ZMGhYZ

if our suggestion(s) worked,  let us know by marking the answer as "Best Answer" right under the comment.This will help the rest of the community should they have a similar issue in the future.  Thank you!
Arun