Can I use variables for objects in my SOQL query? I have the variable like:

public sObject objectvar;

Which gets a record of type Account. How can I use this variable in my SOQL query like:

Select Name from objectvar

Is there a way to do this kind of dynamic query where the object type is dynamic?


Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code. Dynamic SOQL enables you to create more flexible applications. For example, you can create a search based on input from an end user, or update records with varying field names.

The database query method can be used wherever an inline SOQL query can be used, such as in regular assignment statements and for loops. The results are processed in much the same way as static SOQL queries are processed.

You can use simple bind variables in dynamic SOQL query strings. The following is allowed:

String myTestString = 'Account';
List<sObject> sobjList = Database.query('SELECT Id FROM' + myTestString);

Reference document: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm

  • I have myTestString as a Sobject type. Is it possible to use that in Dynamic SOQL? – SfdcBat Apr 27 '16 at 19:34
  • define it in following way List<Account> sobjList – Himanshu Apr 27 '16 at 19:35
  • Can you check my previous question before this question. I am asking this question in that context. I want the query to be dynamic so that I can fit any object type in my query. – SfdcBat Apr 27 '16 at 19:38
  • 1
    it is possible to fit with any type of object – Himanshu Apr 27 '16 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.