For Clause in SOQL (Salesforce Object Query Language)

In Salesforce Object Query Language (SOQL), we have seen different clauses in previous articles. Now, the FOR clause is a unique and advanced feature that improves query performance and functionality in specific scenarios.

In this Salesforce tutorial, we will learn about the FOR clause in SOQL (Salesforce Object Query Language). In that, I will explain the functionality of the FOR clause and how to use it in SOQL queries with different examples.

What is the FOR Clause in SOQL?

In SOQL, the FOR clause is used to control the locking and sharing behavior of records when we query data. It helps with handling two or more operations simultaneously and ensures data consistency in specific scenarios.

To understand it, let’s take an example: Two users trying to resolve the same case ticket (record) simultaneously. For that, we can use the FOR clause to prevent both users from overwriting each other’s updates.

That means the FOR clause is used to lock the selected record during a transaction. When a record is locked, no other process or user can modify it until the current transaction is completed and the lock is released. This ensures that only one user or process can update the record at a time, preventing conflicts or overwrites.

So, using the FOR clause, we can maintain this sequential access, and it helps ensure data consistency and integrity in the Salesforce database.

Types of FOR Clause in SOQL

There are three types of FOR clauses in SOQL. Below, I have explained the types of clauses, and later, we will see a detailed explanation with examples and real-time scenarios.

  • FOR UPDATE: It is used to lock the selected records so other processes cannot modify them until the transaction completes.
  • FOR VIEW: It is used to ensure the query follows the sharing rules of the current user, but doesn’t lock the records.
  • FOR PREFERENCE: It is used to retrieve data while fulfilling the criteria of the sharing rules and is optimized for when the data won’t be modified.

What is the FOR UPDATE Clause in SOQL?

The FOR UPDATE clause in SOQL is used to lock records during a sequence of operations or actions that are executed as a single unit of work to prevent other transactions from being modified until the current transaction is completed.

This mechanism ensures data consistency and avoids conflicts when multiple users or processes attempt to access or modify the same records simultaneously.

  • After using the FOR UPDATE clause, the records returned by the query are locked.
  • Then, other processes must wait for the lock to be released before modifying the records.

Example: FOR UPDATE Clause in SOQL Query

Now, let’s understand the FOR UPDATE clause in SOQL by taking a scenario, and then I will explain how to use it in SOQL queries.

For example, multiple support agents work on the same case records. To ensure that only one agent can update a specific case at a time, we can use the FOR UPDATE clause in the SOQL query.

Now, let’s understand the Apex code below. First, we created an Aoex class with the method name ForUpdateQuery(), in which we created a List collection variable, which we retrieved and stored the case records with the Status set to “New”. Locks apply only to queried records. If our query does not return any results, no locks are applied.

In this SOQL query, we have used the FOR UPDATE clause, which locks all records stored in the list variable.

So when these records are locked, no other user can update them, and also, if the other processes query the same records with the FOR UPDATE clause, they must wait for the lock to be released. Once the DML operation is completed, any subsequent operations will release the lock.

After that, for each loop, we created a case object instance and passed a list variable where we stored all new cases. Then, we updated the case status from ‘New’ to ‘In Progress.’ Till the DML operation is performed to change the case status, the records will be locked, which means other users can’t change them during this duration.

Once the DML operation is executed, the lock is released, and the user who has access to those particular records can modify them.

public class Demo {   
    public void ForUpdateQuery() {
      
        List<Case> CaseList = [ SELECT Id, Subject, Status  FROM Case WHERE Status = 
                                                             'New' FOR UPDATE ];

          for ( Case c : CaseList ) {
                    c.Status = 'In Progress';
                    System.debug ( 'Case ID : ' + c.Id +' '+'Subject : '+c.Subject  +' '+ 'Status : 
                                                          '+c.Status );
                 }
           UPDATE CaseList;
    }
}

In the image below, you can see the query result of all the case records we retrieved from the case object. The status has changed from ‘New’ to ‘In Progress’.

For Clause in SOQL

In this way, we can use the FOR UPDATE clause in SOQL to lock the records that we want to prevent other users from modifying.

What is the FOR VIEW Clause in SOQL?

The FOR VIEW clause in SOQL is used to mark a record as “read” by the current user in the context of tracking operation. Basically, it updates the LastViewedDate field of the queried records without requiring an explicit update operation. This field tracks the last time a user accessed or viewed a record.

  • After using the FOR VIEW clause, Salesforce automatically updates its LastViewedDate field to the current date and time.
  • Unlike FOR UPDATE, it doesn’t lock the records, making it suitable for non-transactional scenarios. No transactional means operations or actions that are not executed, like DML operations.
  • The FOR VIEW clause is structured to track views without modifying the records or their state.

Example: FOR VIEW Clause in SOQL Query

Using a real-time scenario, let’s explore how to utilize the FOR VIEW clause in an SOQL query and understand its functionality.

For example, if we want to track which support agent has viewed the case record and on which date and time, then we can use the FOR VIEW clause. So, this query allows us only to view the records, and when we retrieve the documents using this clause, it automatically updates the LastViewedDate field in a particular object.

SELECT Id, Subject, Status, LastViewedDate, OwnerId FROM Case WHERE Status = 'In Progress' FOR VIEW

In the above SOQL query, we first provided fields that we want to display in the result. In that, we added LastViewedDate, which displays the last viewed date and time. After that, in the WHERE clause, we added a condition so that we can only retrieve cases that are in the In Progress state.

Finally, we added the FOR VIEW clause because if we don’t add this clause to the query, the LastViewedDate field will show the old date when the user viewed the case record. When we execute the query, Salesforce automatically updates the LastViewedDate for each retrieved case to reflect that the user has viewed these records.

FOR VIEW Clause in SOQL Query

In this way, we can use the FOR VIEW clause in SOQL to update the LastViewedDate field of the queried records without requiring an explicit update operation.

What is the FOR REFERENCE Clause in SOQL?

The FOR REFERENCE clause in SOQL is used to identify which records are referenced by a specific field. This is very helpful when we need to find out which child records are related to a parent record. Because this clause returns the IDs of the records that are referenced in another object field, we use this clause to see relationships between objects without having to query the full data.

Example: Use FOR REFERENCE Clause in SOQL Query

Let’s understand the FOR REFERENCE clause in detail using a scenario, and we will create a query to use this clause.

For example, in Salesforce, we know that Account and Contact objects are in a relationship. In that account is the parent object, and the contact is the child object related to the account. Now, we want to find out which accounts have contacts linked to them, but we only need the IDs of the accounts being referenced.

For that, we have a FOR REFERENCE clause in SOQL. Let’s see how to use it in the query to get child records.

SELECT AccountId FROM Contact FOR REFERENCE

In the above query, you can see we only retrieved the account IDs that are referencing the Account object. If you want to see which accounts are duplicates, then we can use the GROUP BY clause to check it.

In the result below, you can see the only IDs displayed, which account have contacts linked to them.

Use FOR REFERENCE Clause in SOQL Query

In this way, we can use the FOR REFERENCE clause in SOQL to determine which child records relate to a parent record.

Conclusion

I hope you have an idea about the FOR clause in SOQL (Salesforce Object Query Language). In that, I have explained the functionality of the FOR clause and its different types. In those types, we have seen their functionality and how to use them in SOQL queries with different examples.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.