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.

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()).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: