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.
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> sobjList = 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.