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