SOQL Record Locking

There may be cases where a pessimistic locking strategy makes sense within your custom Apex script, for example the available inventory statistic on a Stock record may need to be locked while your code works out the correct value to decrement.

The interesting, but rarely used SOQL keyword “FOR UPDATE” can be applied to SOQL query statements to lock the returned records such that only the current call context can modify the records via DML operations.

[sourcecode language=”java”]
Account a = [select Id, Name from Account where City=’Edinburgh’ LIMIT 1 FOR UPDATE];

Results are automatically ordered by ID, a preferred ORDER BY clause is not supported. When applying custom locking, remember to order locks from parent to child and always, always follow the same sequence in all cases, otherwise you open up the possibility of introducing deadlocks.

Remember each Apex call context is an implicit transaction with auto-commit, i.e. committed or rolled-back atomically. For finer, conditional transaction control within a call context use savepoints (Database.setSavePoint()).

%d bloggers like this: