Writing dynamic soql
- johnsontitus
- May 25, 2020
- 1 min read
Dynamic SOQL refers to the creation of a SOQL string at run time 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.
Examples:
Using dynamic select fields:
List<String> fields = new List<String>{'name'};
String soql = 'select Id, ' + String.join(fields, ', ') + ' from Account';
List<Account> objLst = Database.query(soql);
for(Account a : objLst){
System.debug(a.name);
}
Using dynamic where value:
String myTestString = 'Prospect';
List<Account> sobjList = Database.query('SELECT Id, name FROM Account WHERE Type = :myTestString');
for(Account a : sobjList){
}
Account myVariable = new Account(Type='Prospect');
String resolvedField1 = myVariable.Type;
List<Account> sobjList = Database.query('SELECT Id, name FROM Account WHERE Type = :resolvedField1' );
for(Account a : sobjList){
System.debug(a.name);
}

Comments