Queries

Apex Dynamic SOQL

Dynamic SOQL Queries

Apex dynamic SOQL builds queries at runtime with strings.

Introduction to Dynamic SOQL

Dynamic SOQL is a powerful feature in Apex that allows developers to construct and execute SOQL queries at runtime. Unlike static SOQL, where queries are defined at compile time, dynamic SOQL uses strings to build queries based on runtime conditions. This flexibility is particularly useful when dealing with complex query requirements or when the structure of the query is not known until runtime.

When to Use Dynamic SOQL

Dynamic SOQL can be beneficial in situations where:

  • Query conditions are determined by user input or other runtime factors.
  • There is a need to construct flexible queries that adapt to various conditions.
  • The query must be constructed in a loop or iterative process.

However, it is important to use dynamic SOQL cautiously to avoid SOQL injection vulnerabilities.

Basic Example of Dynamic SOQL

In this example, a simple dynamic SOQL query fetches contacts based on a lastName variable. The query string is constructed by concatenating the variable within the query string. This query is then executed using Database.query().

Preventing SOQL Injection

To safeguard against SOQL injection attacks, use the String.escapeSingleQuotes() method. This ensures that any user input is properly escaped, preventing malicious code injection.

Advanced Dynamic SOQL Features

Dynamic SOQL can be further enhanced with features such as:

  • Bind Variables: Use variables directly in the query string to optimize performance and security.
  • Complex Logical Constructs: Build complex queries that include conditional logic and multiple filters.

For instance, you can dynamically adjust which fields are queried based on user preferences.

Conclusion

Dynamic SOQL is a versatile and powerful feature in Apex, enabling developers to create flexible and efficient queries at runtime. By understanding and leveraging dynamic SOQL responsibly, you can enhance the functionality and adaptability of your Salesforce applications.

Queries