Skip to content

Dynamic SOQL: Unlocking Flexibility in Salesforce Queries

Published 18/08/2025

SOQL Apex Hero Image

Dynamic SOQL is a powerful feature in Salesforce that allows developers to construct SOQL queries at runtime. This flexibility enables the creation of more adaptable and responsive applications, as queries can be tailored based on user input or other runtime conditions. In this post, we’ll explore the fundamentals of using Dynamic SOQL, along with best practices and common use cases.

Dynamic SOQL allows you to build queries as strings at runtime, providing the flexibility to adjust query logic based on dynamic conditions. This is particularly useful in scenarios where query parameters are not known until runtime.

A basic example of Dynamic SOQL in Apex might look like this:

String industry = 'Technology';
String query = 'SELECT Id, Name FROM Account WHERE Industry = \'' + industry + '\'';
List<Account> accounts = Database.query(query);

In this example, we construct a SOQL query string to retrieve accounts in the ‘Technology’ industry. The Database.query() method is used to execute the query string, allowing for dynamic query construction.

Bind variables are crucial for enhancing both security and performance in Dynamic SOQL. They offer several benefits:

  • Bind variables separate the query logic from the data values. This means that the data is treated as a parameter rather than part of the query string itself.
  • By using bind variables, you ensure that user input is not directly concatenated into the query string, which is where injection vulnerabilities typically occur.
  • When you use bind variables, Salesforce automatically handles the escaping of special characters. This prevents malicious input from altering the intended structure of the query.
  • For example, if a user input contains a single quote or other special characters, these are automatically escaped, preventing them from breaking out of the intended query context.
  • Besides security, bind variables can also improve query performance by allowing Salesforce to cache and reuse query execution plans, as the query structure remains consistent.

Here’s an example demonstrating the use of bind variables in Dynamic SOQL:

String industry = 'Technology';
String query = 'SELECT Id, Name FROM Account WHERE Industry = :industry';
List<Account> accounts = Database.query(query);

In this example, the :industry syntax is used to bind the variable to the query, preventing SOQL injection and improving query performance.

Dynamic SOQL is ideal for constructing complex queries with multiple conditions:

String industry = 'Technology';
Decimal minRevenue = 1000000;
String query = 'SELECT Id, Name FROM Account WHERE Industry = :industry AND AnnualRevenue > :minRevenue';
List<Account> accounts = Database.query(query);

This query dynamically filters accounts by industry and annual revenue, demonstrating how multiple conditions can be incorporated into a dynamic query.

Dynamic SOQL can also be used to select fields dynamically based on user input or application logic:

List<String> fields = new List<String>{'Id', 'Name', 'Industry'};
String fieldList = String.join(fields, ', ');
String query = 'SELECT ' + fieldList + ' FROM Account';
List<Account> accounts = Database.query(query);

In this example, the fields to be queried are determined at runtime, allowing for flexible data retrieval. As it is important to ensure that the fields being queried are accessible to the current user to maintain security and data integrity, we could incorporate this:

// Define the fields to be queried
List<String> fields = new List<String>{'Id', 'Name', 'Industry'};
// Check field accessibility
List<String> accessibleFields = new List<String>();
for (String field : fields) {
if (Schema.sObjectType.Account.fields.getMap().get(field).getDescribe().isAccessible()) {
accessibleFields.add(field);
}
}
// Join accessible fields into a query string
String fieldList = String.join(accessibleFields, ', ');
String query = 'SELECT ' + fieldList + ' FROM Account';
// Execute the query
List<Account> accounts = Database.query(query);

In this example, before constructing the query, we iterate over the list of fields and check if each field is accessible to the current user using the Schema class. However there other ways to achieve the same outcome like using stripInaccessible.

- Avoid SOQL Injection: Use bind variables to prevent SOQL injection attacks.
- Limit Query Complexity: Keep dynamic queries as simple as possible to maintain performance and readability.
- Use String.escapeSingleQuotes(): When constructing query strings, use String.escapeSingleQuotes() to handle special characters safely.

- User-Driven Searches: Allow users to specify search criteria, dynamically building queries to fetch relevant records.
- Conditional Logic: Implement complex business logic that requires different queries based on specific conditions or user roles.
- Custom Reports: Generate custom reports by constructing queries that adapt to various reporting needs and data structures.


Dynamic SOQL provides Salesforce developers with the flexibility to create adaptable and responsive applications. By understanding how to construct and execute dynamic queries, you can build powerful data-driven solutions that meet diverse business requirements. With best practices in mind, Dynamic SOQL can be a valuable tool in your Salesforce development toolkit.