Queries

SOQL FOR UPDATE

Locking Records

SOQL FOR UPDATE locks records during query execution.

What is SOQL FOR UPDATE?

The SOQL FOR UPDATE clause is used in Salesforce Object Query Language (SOQL) to lock records during query execution. This ensures consistency by preventing other transactions from modifying the records while they are being processed. It is particularly useful in concurrent environments where multiple users or processes may attempt to update the same records simultaneously.

Why Use FOR UPDATE in SOQL Queries?

Using FOR UPDATE can help prevent race conditions where two processes attempt to modify the same data at the same time. By locking the records, you can ensure that your transaction has exclusive access to the data, thus maintaining data integrity and consistency.

Basic Syntax of SOQL FOR UPDATE

How FOR UPDATE Works in SOQL

When you include the FOR UPDATE clause in a SOQL query, Salesforce places a lock on the selected records. This lock will remain until your transaction is completed, either by committing the changes or by rolling back the transaction. During this time, other transactions are prevented from modifying the records, although they can still read them unless another FOR UPDATE is used concurrently.

Example: Using FOR UPDATE in a Trigger

Consider a scenario where you have a trigger that updates contact information. To ensure that no other process can change the contact records while your trigger is executing, you can use FOR UPDATE to lock the records.

Considerations When Using FOR UPDATE

While FOR UPDATE is a powerful tool, it should be used judiciously. Locking records can lead to contention and potential deadlocks if not managed properly. It is important to design your application logic to minimize the duration for which records are locked and to handle any potential exceptions or errors gracefully.

Previous
OFFSET