SOQL allows us to fetch data from a Salesforce org. There are two ways in which you can do that: 1) Dynamic queries, and 2) Static queries.
Dynamic Query
To make a query to the Salesforce database when the query differs based on certain conditions, we use dynamic SOQL queries.
Syntax:
List<sObject> sobjList = Database.query(string);
For Example,
String Field1 = ‘Id’;
String Field2 = ‘Name’;
String ObjectName = ‘Account’;
String query = ‘Select ’ + Field1 + ‘, ‘ + Field2 + ‘ From ‘ + ObjectName ;
// Actual query would look like [Select Id, Name From Account]
List<Account> accList = Database.query(query);
Static Query
To make a query to the database where only filters need to be dynamically assigned and the Object/Field names are going to be constant, we use static SOQL queries.
Syntax:
List<sObject> sobjList = [Select Id, Name From Sobject Where Name = :variable];
For Example,
String accName = ‘White Gloves’;
List<Account> accList = [Select Id, Name From Sobject Where Name = :accName];
Conclusion
While a static query works in most use cases, there are some complex requirements that force you to use a Dynamic Query. However, a static query is always preferred as it is lightweight and more secure.
To learn more about SOQL and Salesforce, check out, “SOQL Injection and Prevention.”
Additional Resources:
- Salesforce Developers Forum: What is diff between Static soql and Dynamic soql queries?
Cover Photo by Oskar Yildiz on Unsplash