top of page

Dynamically Pass Bind Variables to a SOQL Query

Salesforce Apex is a strongly-typed, object-oriented programming language that is used to write custom business logic in Salesforce. It provides a rich set of APIs to interact with the Salesforce data and platform, including the ability to run dynamic SOQL (Salesforce Object Query Language) queries.

In Apex, you can run SOQL queries using the Database.query method. However, this method does not provide a way to pass bind variables, which can make your code vulnerable to SOQL injection attacks and can make it more difficult to parameterize your queries.

To solve this problem, Salesforce provides the Database.queryWithBinds method, which allows you to run SOQL queries with bind variables. This method provides a way to pass variables to your SOQL queries, making it easier to build dynamic and secure queries.

Using the Database.queryWithBinds method is straightforward. You start by defining your SOQL query as a string, and then you create a Map of bind variable values. The Map keys should match the names of the bind variables in your SOQL query, and the values should be the actual values that you want to pass to the query.

Here's an example of how to use the Database.queryWithBinds method in Apex:

In this example, the soqlQuery string contains a bind variable :accountId, and the bindVariables map contains a key-value pair with the key 'accountId' and the value accountId. When the Database.queryWithBinds method is called, it substitutes the value of accountId for the bind variable in the query and returns a list of Account records that match the specified Id.

Using bind variables with Database.queryWithBinds provides several benefits:

  • Security: By using bind variables, you can prevent SOQL injection attacks, which are a type of security vulnerability that can occur when user-supplied data is used directly in SOQL queries.

  • Parameterization: By passing variables to your SOQL queries, you can more easily parameterize your queries, which makes it easier to build dynamic and reusable code.

  • Performance: Using bind variables can also improve performance, as Salesforce can cache the query results for each unique set of bind variable values, reducing the need to recompile the query each time it is run.

There are 3 methods with binds Database.queryWithBinds, Database.getQueryLocatorWithBinds, and Database.countQueryWithBinds methods.

In conclusion, the Database.queryWithBinds method provides an easy and secure way to run dynamic SOQL queries in Salesforce Apex. Whether you're building custom business logic or integrating with external systems, this method can help you write more efficient, secure, and reusable code.

5,477 views0 comments


bottom of page