I have an SObject say Account which has some not null fields. I want to select all the accounts matching those values. Is there a way I can create a dynamic SOQL query for this.

Suppose the Account object is like this:

Account anAccount = new Account();
anAccount.Name = "sample"
anAccount.CustomName__c = "custom sample"

//Match all account matching above criteria
List<Account> matchingAccounts = [SELECT id from Account where Name=:'sample' AND CustomName__c=:'custom sample'];

I want to make above query dynamically using anAccount instance.

2 Answers 2


You need to build a dynamic SOQL query using the object metadata on the object itself.

Using these methods you can get and set methods on an object dynamically as well as get the metadata objects. You can loop through the field metadata to get field names and test the object to see if they are not null. If not, include them in the query.

The general idea is to build the query by selecting the fields you want from the object, then dynamically building the WHERE. Loop through the fields on the object and call Object value = anAccount.get(fieldName) to see the contents. If not null, add the field to the where: 'AND ' + fieldName + ' = \'' + value + '\''

For a more robust example, see the describeSObjects() documentation.

  • Be great if where you say "using these methods" you could link to the section of the document... Just a link to the 450 page dev guide doesnt really help!
    – dacology
    Commented Jan 13, 2017 at 23:20
  • @dacology I am not sure if it is even possible to link to an anchor in a PDF.
    – user6861
    Commented Jan 14, 2017 at 3:14

Sure! You can use DML database methods but you have to escape the single quotes. There is a bunch of code on this page for creating a dynamic search app.

You would use something like the following:

List<Account> matchingAccounts = Database.query('SELECT id from Account where Name = \''+String.escapeSingleQuotes(your-account-name-var)+'\'' AND CustomName__c = \''+String.escapeSingleQuotes(your-customer-name-var)+'\''');
  • I don't already know the fields to query. The name and CustomName__c are just for example. I have to get these from the account object instance
    – vishesh
    Commented Apr 21, 2014 at 20:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .