January 31, 2021

FOR UPDATE Clause in SOQL

Hello Trailblazers !

In this blog post, we will see what is FOR UPDATE clause in SOQL, when to use it and how to use it. FOR UPDATE clause in SOQL is basically used to lock sObject records while they are being updated in order to prevent race conditions and other thread safety problem.


When sObject record is locked, no other client or user is allowed to make updates either through code or salesforce user interface.

  • Syntax
List<Account> accList = [SELECT Id, Name FROM Account LIMIT 10 FOR UPDATE];
When you run above query, Account records will be locked for this transaction until the transaction completes.
  

  • Considerations while using FOR UPDATE

  1. You can not use ORDER BY in any SOQL query that used locking.
  2.  It not only locks the queried records but also related records.
  3. The record locks that are obtained in Apex via FOR UPDATE clause are automatically released when making callouts.
  4. If you attempt to lock a record currently locked by another client, your process waits for the lock to be released before acquiring a new lock. If the lock isn’t released within 10 seconds, you will get a QueryException. Similarly, if you attempt to update a record currently locked by another client and the lock isn’t released within 10 seconds, you will get a DmlException.

Resources



No comments:

Post a Comment