Locking Record in Salesforce

We can lock record in Salesforce to prevent user or client allow to make update either through code or UI. So lock record can’t be changed during the lock period.

Locking Statement –

In Apex, you can use FOR UPDATE to lock sObject record.

To lock a set of sObject records in Apex, embed the keywords FOR UPDATE after any inline SOQL statement. For example, You are querying for two accounts, also locks the accounts that are returned:

Account [] accts = [ SELECT Id FROM Account LIMIT 2 FOR UPDATE ];

NOTE- You can’t use the ORDER BY keywords in any SOQL query that uses locking.

Locking in a SOQL For Loop

The FOR UPDATE keywords can also be used within SOQL for loops.

for (Account[] accts : [SELECT Id FROM Account FOR UPDATE]) {
    // Your code

Locking Consideration-
  1. While the records are locked by a client, the locking client can modify their field values in the database in the same transaction. Other clients have to wait until the transaction completes and records are unlocked .
  2. Other clients can still query the same records while they’re locked.
  3. If you try 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.
  4. If you try to update a locked record  by another client and the lock isn’t released within 10 seconds, you will get a DmlException.
  5. If a client try to modify a locked record, the update operation might succeed if the lock gets released within a short amount of time after the update call was made.                 But there might be a chance of the second client update call data will overwrites by the old locked data from first client. To prevent this from happening, the second client must lock the record first.The locking process returns a fresh copy of the record from the database through the SELECT statement.
  6. When you perform a DML operation on one record, related records are locked in addition to the record in question.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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