How to do/use DML Query Multiple Times in a Batch Apex Salesforce?

Lets look at the solution!

Shubham Rajput
3 min readMar 2, 2024
Salesforce Specialists

Yes you heard right we can query multiple times in Apex Batch Class before start() methods of batch apex.

Did you found yourself in trouble, came across a requirement where you have to query two times to fetch data for logic validation & then data update.

Sounds a bit of confusing??? Let me make this simple for you

Let’s Assume There are three objects

1) Account

2) Contact

3) Opportunity

As shown in below diagram,

Requirement Example | CodeBiceps — Shubham Rajput

Account & Opportunity have One : Many [Parent : Child] relationship. Similarly, Account & Contact have One : Many [Parent : Child] relationship.

As a single query in batch class on Opportunity Object you can only apply subquery for Account Object because Opportunity has a relationship with Account.

But there is no direct relationship between Contact & Opportunity object.

And here is the root of the problem.

Okay.. Now get out of this rid what we can do,

Requirement Solution | CodeBiceps — Shubham Rajput

Batch Apex Provide us a magical ability to define & use Static block with Static final Map/Set/Variables etc. inside Batch Apex class. Using “Static” block we can query twice, thrice, quadrice and as many as you want.

So in order to resolve this issue, we can query on Contact Object separately, Can store fields from Contact Object query to Map/Set/Variables etc. & can utilize those variables inside main batch apex execute method’s logic in order to update the queried filtered Opportunity Object’s record.

Solution Steps:

Step 1: In Static block Query Contact with Records AccountId WHERE Level = ‘Primary’

Step 2: Store AccountId in Set/Map/Any suitable Data Structure which declared as static final.

Step 3: In Start block of batch Query Opportunity Record WHERE Stage = ‘Value Proposition’ AND Asset.Type = ‘Technology Partner’

Step 4: Execute the logic only id AccountId is present in Set/Map contains AccountId of Queried Contact records.

And here you go…

You can refer below code for your help.

Code Approach | CodeBiceps — Shubham Rajput

To access the code click on below link & don’t forget to follow the git hub account for such outstanding salesforce solutions.

Code Access Link — https://github.com/shubhamrajput0369/How-to-do-use-DML-Query-Multiple-Times-in-a-Batch-Apex-Salesforce-

Follow CodeBiceps Insta Page & Shubham Rajput 🌩️ for more such tips & updates. You can write an email to me for any help or your reviews.

CodeBiceps: https://www.instagram.com/code.biceps

Shubham Rajput🌩️: https://www.linkedin.com/in/shubhamrajputsde

Email: shubham.rajput0369@gmail.com

Stay Connected, Stay Healthy & Spread Knowledge.💫

Till that signing off, The CodeBiceps /> : )

--

--