Examples
SOQL Dynamic Query
Building a Dynamic Query
SOQL dynamic query builds filters in Apex at runtime.
Introduction to SOQL Dynamic Queries
SOQL (Salesforce Object Query Language) dynamic queries allow developers to construct queries in Apex at runtime. This is particularly useful when the query needs to change based on user input, application state, or other conditions. Unlike static SOQL queries, dynamic queries provide flexibility and adaptability in your Salesforce applications.
Why Use Dynamic SOQL?
Dynamic SOQL is useful in scenarios where query parameters are not known until runtime. Here are some common use cases:
- User-Driven Searches: When users can input various search criteria.
- Conditional Logic: When query conditions depend on other data or user interactions.
- Reusability: When you want to create a general query function that can be reused with different parameters.
Constructing a Dynamic SOQL Query
To construct a dynamic SOQL query in Apex, you build a query string and then execute it using Database.query
. Here’s a step-by-step guide:
In this example, we are dynamically constructing a query string to fetch accounts in the technology industry. This query can be modified easily by changing the criteria
variable.
Handling Dynamic Query Parameters
When constructing dynamic queries, it’s essential to handle user input carefully to prevent SOQL injection attacks. You can use the String.escapeSingleQuotes()
method to sanitize input:
By escaping single quotes, you ensure that any input provided by the user does not break the query or introduce security vulnerabilities.
Dynamic SOQL with Multiple Conditions
Sometimes, you may need to build queries with multiple conditions. You can do this by appending conditions to the query string using logical operators:
In this case, the query selects accounts from the technology industry with an annual revenue greater than $1,000,000. The conditions are joined using the String.join()
method with an AND
operator.
Best Practices for Dynamic SOQL
Dynamic SOQL offers flexibility but requires careful implementation. Here are some best practices:
- Use Bind Variables: Utilize bind variables whenever possible to improve query performance and readability.
- Sanitize Input: Always escape user input to prevent SOQL injection.
- Consider Limits: Be mindful of governor limits and ensure that dynamic queries do not exceed them.
- Debugging: Use
System.debug
to print the query strings during development for easier debugging.
Examples
- Previous
- Aggregate Query
- Next
- Bulk Query