Development questions
How does FOR UPDATE work in SOQL, and how does it lock records to prevent race conditions?
FOR UPDATE places a pessimistic lock on the returned records for the rest of the transaction. Other transactions attempting to update them wait (up to ~10 seconds) and then fail with UNABLE_TO_LOCK_ROW.
This prevents race conditions such as two processes reading the same balance, both incrementing, and overwriting each other.
apex
Account a = [SELECT Id, Credit__c FROM Account WHERE Id = :accId FOR UPDATE];
a.Credit__c += 100;
update a;
Restrictions: can't be used with ORDER BY in some cases like aggregates, can't be used in a for loop of QueryLocator type, and should be used in short transactions to avoid lock contention.
soqlkeywordslocking
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?