Salesforce Object Query Language(SOQL) is useful in querying the records from database.com
depending on the requirement. There are 2 types of SOQL statements: Static SOQL and Dynamic SOQL.
Static SOQL:
- The Static SOQL statement is written using [] (array brackets). This statement is similar to IINQ (Ion Integrated Query).
- It is used in the condition where you don’t have any dynamic changes in the SOQL query. We don’t use Static SOQL when the field name or where the condition is needed to be dynamically defined.
Example for Static SOQL query:
Contact[] contacts = [SELECT testfield__C, FirstName, LastName FROM Contact WHERE LastName = 'Dhanya'];
Dynamic SOQL:
- It is used to refer to the SOQL string creation at run time with Apex code.
- Dynamic SOQL allows you to create more flexible applications. For example, you are able to create a search based on end-user input or update records with different field names.
- To create a Dynamic SOQL query at run time using a Database.query() method, in any one of the given below ways:
- Return a single sObject when the single record is returned by a query.
sObjects s = Database.query(string_limit_1);
- Return a list of sObjects when more than a single record is returned by a query.
List<sObject> sobjList = Database.query(string);
Example for Dynamic SOQL query:
String myTestString = 'TestName';
List<sObject> sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString');