Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

If you want to dynamically pass bind variables to a SOQL, with Spring 23 release, you will get more power. In this blog post, I will share some examples, but if you prefer to watch videos instead of reading the post, you can do that by watching the video below, which I have published on my Youtube Channel – Technical Potpourri

Introduction

With the new Database.queryWithBindsDatabase.getQueryLocatorWithBinds, and Database.countQueryWithBinds methods, the bind variables in the query are resolved from a Map parameter directly with a key rather than from Apex code variables. As a result, it’s not necessary for the variables to be in scope when the query is executed.

Example 1

As you can see in the above code, I am creating a map acctBinds and storing the account name in Key Value fashion. Now in the next line, where I am executing the soql query to fetch the account, I am using the Map name and Key name to dynamically bind the values to the query. This is very cool.

But as you might have been thinking, why this map is having one value just? Having a map and not storing multiple values, doesn’t make sense. So in my next example, I will show you how you can store multiple values in the map and then use the same map to dynamically bind values to the soql query.

Example 2

This time as you can see, I am storing multiple values in the map acctBinds and then using the same way to dynamically pass values to the soql query. This approach will help you to write more optimized code.

Conclusion

This is a very useful feature which developers can take advantage of now. But with power, comes responsibilities. So always recommended to follow the best practices by making your query optimized.

As of now, we can use only below methods to implement dynamic binding.

  • Database.queryWithBinds
  • Database.getQueryLocatorWithBinds
  • Database.countQueryWithBinds

Please read the official documentation here.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

2 Comments

  1. Jonathan barr

    This is super helpful. Your contents and youtube channel is full of important contents. I love your content. Huge respect for you to spend time and sharing your knowledge with others.

    Reply
    • Sudipta Deb

      Thank you Jonathan. Appreciate your comment.

      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *