SOQL Query in Apex Programming

We used SOQL(Salesforce Object Query Language) to retrieve the data from the Salesforce database according to the specified conditions and objects.  These objects can be both standard and custom. Similar to all Apex code, SOQL is also not case-sensitive. SOQL is also used in Apex to query Salesforce data stored in the database.

In this Salesforce tutorial, we will learn about SOQL queries in Apex programming. In that, I will explain the benefits of using SOQL in Apex and how to use SOQL query in Apex programming.

Why We Use SOQL Query in Apex Programming?

SOQL is used in Apex to retrieve data from Salesforce objects efficiently. It enables users to query specific records and fields from standard or custom objects based on conditions, making it essential for interacting with the Salesforce database.

SOQL supports filtering, ordering, aggregation, and relationship queries, allowing for powerful data retrieval capabilities. It is commonly used in triggers, batch Apex, and controllers to integrate database operations with business logic.

By retrieving only the required data, SOQL helps optimize performance while respecting Salesforce’s governor limits, ensuring scalable and efficient application development.

Use SOQL Query in Apex Programming

Salesforce provides developers and administrators with the feature to fetch/retrieve information about users using the Apex class, VF pages, Aura, and LWC components, and the global variable($User).

Example: Retrieve Current User Records Using SOQL in Apex

Now, let’s take an example: we want to display the currently logged-in user’s records using SOQL. When we try to retrieve records from the SOQL editor on the developer console, we cannot get current user details. For that, we must use Apex classes in Salesforce.

Here, I created an Apex class with a method and then used the UserInfo class with the getUserId() method, which returns the currently logged-in user ID. Then, I created a declared User object with variable u and wrote an SOQL to retrieve the user records, and I passed that ID into the SOQL query, which retrieves the user details.

public class GetUserDetails {  
    
    public void userdetails(){
        
        Id userId = UserInfo.getUserId();

        User u= [ SELECT Name, Id, Email, Profile.Name FROM User WHERE Id = :userId ];   
    
        system.debug (' Current User ID: ' +u.Id);
        system.debug (' Name: ' +u.Name);
        system.debug (' Profile Id: ' +u.Profile.Name);        
    }          
} 

In the image below, you can see what we cannot do with the SOQL editor, which we can achieve using the SOQL query in Apex programming. We retrieved records of currently logged-in users and displayed the information in SOQL results.

SOQL Query in Apex Programming

In this way, we can get whatever details we want of currently logged-in users, which we can retrieve using the UserInfo class method and SOQL query in Salesforce Apex.

Example: Use SOQL Query to Deactivate Users in Salesforce Apex

In the following image, you can see the maximum number of active Identity User profiles. We will create a class to deactivate all identity user profiles.

Active Users in Salesforce

Here, I created an Apex class with a method. In that method, I created a list to store the list identity profile user records, and using SOQL, I retrieved user records and stored them in the userlist variable.

  • SOQL: In SOQL, I used the WHERE clause to retrieve specific types of records.
  • for loop: In a for loop, we need to create a User object instance and pass the retrieved active user list to the object instance. Then, using the object instance, we check whether users in the list are active; if they are active, then deactivate all users.

Then, update the user list to save the deactivated user in the User object.

public class DeactivateMultipleUsers {
    
    public void deactivateUsers(){
        
        List<User> userslist = [Select ID, Name, IsActive From User WHERE Profile.Name = 'Identity User'];
        
        for(User user : userslist){          
            if(user.IsActive = true){
                user.IsActive = false;
           }           
        }
           UPDATE userslist;  
           system.debug('Identity Users has been Deactivated successfully');
    }       
}
Use SOQL Query to Deactivate Users in Salesforce Apex

After executing the Apex code, navigate to the user list view and refresh the page. You will see that all users with the Identity User profile have been deactivated.

Deactivated users from Salesforce Apex

Example: Use SOQL Query to Retrieve and Update Lead Records in Apex

For example, I want to store records of lead objects whose lead Industry is ‘Technology,’ and we need to update the Status of all those records to ‘Close-Converted.

Here, you can see that before creating the Apex code, the technology industry had a different status.

Use of List Collection in Salesforce Apex

Here, I declared a class, and in that class, I created a list collection of lead records. Using the SOQL query, we retrieved all leads in the industry, which is a technology, and stored the query results in a list.

Now, we want to update all lead statuses to closed converted, which are from the technology industry. We need to add a loop so that we can assigna status to all lead records and update the list.

public class ListCollection {
    
    public void UpdateLeadRecords(){
        
        List<Lead> LeadsList = [Select Id, Name from Lead Where Industry='Technology'];
        try{
            for(Lead l : LeadsList){
                l.Status = 'Close-Converted';
             }
            Update LeadsList;
        }
        Catch(Exception e){
            e.setMessage('Something Went Wrong');
         }   
    }
}

After the Apex code is executed, you can see in the lead object all the records with the technology industry’s status are close-converted.

How to Use List Collection in Apex Salesforce

In this way, we can use the list collection in Salesforce Apex.

Example: Use SOQL with WHERE Clause in Apex

For example, we want to develop Apex code to display the number of records for any particular user, with opportunity stage name = ‘closed won’.

Here, I created a list in which I stored opportunity records using SOQL query, and to apply the condition to get particular records, we used the WHERE clause. Now, using the if condition, we will check whether there is any record available on the list. If a record is available, then execute the if block, which returns the record count.

public class Demo {
    
    public void IfConditionDemo() {

        Id ownerId = '0055i000004xf7XAAQ';
        List<Opportunity> oppList = [SELECT Id, StageName  FROM Opportunity WHERE = OwnerId: ownerId  AND StageName = 'Closed Won'];


        if ( !oppList.isEmpty() ) {
            Integer oppoCount = oppList.size(); 
            System.debug( 'Total number of "Closed Won" Opportunities: ' + oppoCount );
        }
    }
}
Conditional Statements in Salesforce Apex

Conclusion

I hope you have got an idea about SOQL queries in Apex programming. In that, I have explained the benefits of using SOQL in Apex and how to use SOQL query in Apex programming. In that, I have explained the benefits of using SOQL in Apex and how to use SOQL query in Apex programming.

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.