Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code.

To create a dynamic SOQL query at runtime, use the database query method, in one of the following ways:

  • Return a single sObject when the query returns a single record:

    sObject S = Database.query(string_limit_1);
  • Return a list of sObjects when the query returns more than a single record:

    List<sObject> L = Database.query(string);

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.

Dynamic SOQL results can be specified as concrete sObjects, such as Account or MyCustomObject__c, or as the generic sObject data type. At runtime, the system validates that the type of the query matches the declared type of the variable. If the query does not return the correct sObject type, a runtime error is thrown. This means you do not need to cast from a generic sObject to a concrete sObject.

Useful Documentation

history | excerpt history