Table of Contents
Introduction
We create apex triggers to automate our task which helps us to perform operations before trigger as well as after the trigger.
We can create apex triggers with SOQL and without SOQL as well to do multiple operations like insertion, updation, deletion, or undeletion of records in our org.
How to use SOQL in Apex triggers?
We should never write our SOQL query in for loop. It will not put us in trouble for a single record, but when it comes to bulk records, we might get an exception. Why?
Salesforce has provided us with some governor limits beyond which if we try to go, will get an exception.
So, as per governor limits, we can have only 100 SOQL queries in synchronous and 200 in async.
And if we write our SOQL in for loop, there are more chances that we exceed the governor limit.
ALWAYS AVOID WRITING SOQL INSIDE A FOR LOOP!!
Example
//Prevent account record deletion if Account has an associated opportunity trigger PreventAccDeletionIfHasAssociatedOpp on Account (before delete) { Set<Id> accIds = new Set<Id>(); for(Account acc : Trigger.old){ if(!String.isEmpty(acc.Id)){ accIds.add(acc.Id); } } List<Opportunity> oppList = [SELECT Id, AccountId, Name FROM Opportunity WHERE AccountId IN :accIds]; if(oppList.size() > 0){ for(Account acc : Trigger.old){ if(Trigger.isBefore && Trigger.isDelete){ acc.addError('Account record cannot be deleted since it has associated opportunity'); } } } }
Explanation
In this example, we have written SOQL to fetch Opportunity records whose related account record (AccountId) is the same as that of Accounts that we are deleting.
Importance of using SOQL in Apex triggers
Let’s talk about both the cases with or without SOQL one by one in brief.
1. Apex Triggers Without SOQL
If we are creating triggers without SOQL, then we can access only those records which are being inserted or updated.
2. Apex Triggers With SOQL
If we are creating triggers with SOQL, then not only we can access records that are being inserted or updated but access opens up to all the records present in org.
We can access all the records from our org if we use SOQL in apex triggers.
Any operation can be performed on those records.
0 Comments