Friday, March 14, 2025

Interview Questions on Salesforce Apex Part-1

 1) How do SOQL List and SOQL For Loop differ in terms of memory handling?

SOQL List loads all queried records into memory at once, which can quickly exceed the heap size limit if too many records are queried.

SOQL For Loop fetches records one at a time in smaller chunks, making it more efficient and reducing the risk of hitting the heap size limit.

2) What are the potential issues when querying large datasets using SOQL List?

Querying large datasets with SOQL List may result in heap size limit errors if the total size of the data exceeds 6 MB for synchronous operations. To avoid this, you should use SOQL For Loop, which processes records in smaller chunks.

3) How would querying parent-child data affect the use of SOQL For Loop?

When querying parent-child data in Salesforce, if there are more than 200 child records in a relationship, an error like "Aggregate query has too many rows for direct assignment" might occur. This can be avoided by using a nested loop structure.

Incorrect approach (will throw error if there are more than 200 child records):

for(Account obj : [SELECT id, (SELECT id, name FROM contacts) FROM account LIMIT 1]) {

    list<Contact> conList = obj.contacts;  // Error if more than 200 contacts

}

Correct approach (avoids error by iterating over child records inside the loop):

for(Account obj : [SELECT id, (SELECT id, name FROM contacts) FROM account LIMIT 1]) {

    for(Contact con : obj.contacts) {

        // Process each contact record

    }

}

4) Can you explain the heap size limit error with an example?

Let's say you're querying 50,000 records from the Contact object, and each record takes up 2 KB. The total memory required would be 50,000 * 2 KB = 100 MB. Since the maximum heap size limit for synchronous operations is 6 MB, this would exceed the limit, causing a heap size error. This is why SOQL For Loop should be used, as it processes each record individually.

5) Why are Governor Limits enforced in Apex?

Governor Limits are enforced in Apex to ensure that code runs efficiently in Salesforce's multitenant environment. They prevent one tenant from consuming too many resources, which could negatively impact others sharing the same instance.

7) What is the maximum number of records that can be returned by a SOQL query in a synchronous transaction?

A synchronous SOQL query can return a maximum of 50,000 records. If this limit is exceeded, a runtime exception will occur.

8) How many DML statements can be executed in a single transaction?

You can execute up to 150 DML statements in a single transaction, whether it's a synchronous or asynchronous operation.

9) What is the maximum heap size for synchronous operations in Apex?

The maximum heap size for synchronous operations in Apex is 6 MB. If the heap size exceeds this limit, an exception will occur.

10) How many future methods can be invoked in a single Apex transaction?

A maximum of 50 future methods can be invoked per Apex transaction, but for batch/future operations, only 50 queueable jobs can be invoked.

Friday, March 7, 2025

Master Interview questions on apex triggers in salesforce Part-3

 13) What are the the context variable available with before insert event?

Only Trigger.new is available.

Tags: #Interview questions on triggers in salesforce with answers, #Scenario based Interview Questions on triggers in Salesforce

14) What are the the context variable available with after insert event?

Trigger.new and Trigger.newMap.

15) What are the the context variable available with before update event?

Trigger.new, Trigger.old, Trigger.newmap and Trigger.oldmap

16) What are the the context variable available with after update event?

Trigger.new, Trigger.old, Trigger.newmap and Trigger.oldmap

17) What are the the context variable available with before delete event?

Trigger.old and Trigger.oldMap.

18) What are the the context variable available with after delete event?

Trigger.old and Trigger.oldMap.

Tags: #Interview questions on triggers in salesforce with answers, #Scenario based Interview Questions on triggers in Salesforce

19) What are the the context variable available with after undelete event?

Trigger.new and Trigger.newMap.

Friday, February 28, 2025

Master Interview questions on apex triggers in salesforce Part-2

 7) How many trigger we should write on one object?

 We should always follow the best practice and consider writing one trigger per object. If we have more than one trigger per object on same event say before insert than we cannot guarantee the order of execution.  

8) What is the difference between database.insert and insert?

 Using insert if one record fails entire operation is stopped and none of the record is inserted into database, whereas with databse.insert partial insertion is supported.

9) Is it possible to call batch class from trigger.

Yes.

10) What is the condition to call a method from trigger which is making callout?

The callout should be asynchronous.

11) What will you do if a method inside apex class need to be executed only when it is getting called from trigger?

We will use trigger.isexecuting in apex class to check if the method inside apex class is getting called from trigger and will execute the method if getting called from trigger.

12) What is "Trigger Handler Framework Salesforce"?

Refer article: Trigger Handler Framework Salesforce

Friday, February 21, 2025

Master Interview questions on apex triggers in salesforce Part-1

1) What is trigger in Salesforce and what are trigger events?

A Salesforce trigger is a piece of Apex code executed before or after a specific action is performed on a Salesforce object, such as insert, update, or delete. Triggers are primarily used for automating tasks like validation, preventing incorrect data entry, or updating related records.

Trigger Events:

Before Insert: Fires before a record is inserted.

Before Update: Fires before an existing record is updated.

Before Delete: Fires before a record is deleted.

After Insert: Fires after a record is inserted.

After Update: Fires after a record is updated.

After Delete: Fires after a record is deleted.

After Undelete: Fires after a record is undeleted.

Each of these events corresponds to a specific stage in the lifecycle of a record, allowing you to implement logic tailored to that stage.

 2) What are trigger context variables in Salesforce? 

Following are the available Trigger Context Variables:

trigger.isbefore()

Checks if the trigger is in before mode. If the trigger is in before mode, it will return true.

trigger.isafter()

Checks if the trigger is in after mode. If the trigger is in after mode, it will return true.

trigger.isupdate()

Checks if the trigger is in update mode. If the trigger is in update mode, it will return true.

trigger.isdelete()

Checks if the trigger is in delete mode. If the trigger is in delete mode, it will return true.

trigger.isinsert()

Checks if the trigger is in insert mode. If the trigger is in insert mode, it will return true.

trigger.isundelete()

Checks if the trigger is in undelete mode. If the trigger is in undelete mode, it will return true.

trigger.isexecuting()

Checks if the Apex class method is being called from an Apex trigger. If it is being called, it will return true.

trigger.new()

Stores a new list of records.

trigger.newmap()

Stores new records with their IDs.

trigger.old()

Stores the old list of records.

trigger.oldmap()

Stores old records with their IDs.

operationType

Returns an enum of type System.TriggerOperation, corresponding to the current operation.

Possible values of the System.TriggerOperation enum are: BEFORE_INSERT, BEFORE_UPDATE, BEFORE_DELETE, AFTER_INSERT, AFTER_UPDATE, AFTER_DELETE, and AFTER_UNDELETE.

size

The total number of records in a trigger invocation, including both old and new records.

3) What is the difference between Trigger.new and Trigger.old and Trigger.newmap and Trigger.oldmap ?

Trigger.new returns new records and Trigger.old return data before updates were done.

 Trigger.newmap returns new records with id's and Trigger.oldmap return data before updates were done with id's.

4) Is the id of record changes if we undelete a deleted record?

No, It has the same id.

5) What is the use of trigger.isexecuting?

Suppose we have a method in apex class and we want this method to run only when the method is getting called from apex trigger than we can make use of trigger.isexecuting in apex class to check if the method is getting called from trigger .

Tags: #Interview questions on triggers in salesforce with answers, #Scenario based Interview Questions on triggers in Salesforce

6) How to restrict trigger to fire only once(Recursive trigger)? 

Refer article : How to avoid recursive trigger in Salesforce?

Friday, February 14, 2025

Salesforce Integration Interview Questions on REST API Part-8

1) What is the difference between @HttpPatch and @HttpPut annotations in Salesforce?

@HttpPatch is used to partially update a resource, meaning it modifies only specific fields of the resource without replacing it entirely.

@HttpPut is used to fully replace or update the entire resource with the provided data, meaning it requires the full object to be replaced.

2) What is the purpose of the @RestResource annotation in Salesforce?

The @RestResource annotation is used at the class level to expose an Apex class as a REST resource. It is required for creating custom RESTful services in Salesforce, allowing external applications to interact with Salesforce data via HTTP requests. The urlMapping parameter defines the URL pattern for the resource.

3) What are different Apex REST annotations in Salesforce?

1. @RestResource
This annotation is used at the class level to expose an Apex class as a REST resource. The class must be defined as global, and the urlMapping parameter specifies the URL pattern to access the resource.

2. @HttpDelete
This annotation is used to delete a specified resource via a DELETE request. It marks the method as handling HTTP DELETE operations.

3. @HttpGet
This annotation is used to retrieve a specified resource via a GET request. The method marked with @HttpGet is responsible for fetching data from Salesforce.

4. @HttpPatch
This annotation is used to partially update a resource. It modifies only specific parts of the resource, as specified by the incoming request.

5. @HttpPost
This annotation is used to create a new resource in Salesforce via a POST request. It is commonly used to create new records.

6. @HttpPut
This annotation is used to either create or fully update a resource. It replaces the entire resource with the data received in the request.

4) What is the RestRequest class in Salesforce, and what are some of its key methods?

The RestRequest class in Salesforce is used to access incoming requests in Apex REST web services. It provides several methods to handle different aspects of an HTTP request. Some key methods include:

headers: Returns the headers received by the request (Map<String, String>).
httpMethod: Returns the HTTP method used for the request (String), such as GET, POST, DELETE, etc.
params: Returns the parameters received by the request (Map<String, String>).
remoteAddress: Returns the IP address of the client making the request (String).
requestBody: Returns or sets the body of the request (Blob).
requestURI: Returns or sets everything after the host in the HTTP request string (String).
resourcePath: Returns the REST resource path for the request (String).

5) What is the RestResponse class in Salesforce, and what are some of its key methods?

The RestResponse class in Salesforce is used to pass data from an Apex RESTful web service method to the HTTP response. It has several key methods:

responseBody: Returns or sets the body of the response (Blob).
headers: Returns the headers to be sent in the response (Map<String, String>).
statusCode: Returns or sets the HTTP status code for the response (Integer). Common status codes include 200 (OK), 201 (Created), 400 (Bad Request), etc.

For example, if you want to change the default status code of a RESTful service response, you can modify the statusCode property of the RestResponse class, like setting it to 201 (Created) instead of 200 (OK).

6) What is the purpose of the @HttpGet annotation in Salesforce, and how is it used in Apex?

The @HttpGet annotation in Salesforce is used to expose an Apex method as a RESTful GET service. This annotation allows external systems to retrieve data from Salesforce by making an HTTP GET request to the defined URL. The method must be defined as global static within a class annotated with @RestResource. For example, a method annotated with @HttpGet can fetch records like an Account based on an ID provided in the request URL.

7) Can you provide an example of how the @HttpGet annotation works in a Salesforce Apex class?

Here's an example of how the @HttpGet annotation works in an Apex class:

@RestResource(urlMapping='/getAccountOnExternalIdtofetchsinglerecord/*')
global with sharing class getAccounttoSingleRecord {
    @HttpGet
    global static Account fetchAccount() {
        RestRequest req = RestContext.request;
        string accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account obj = [SELECT Id, Name FROM Account WHERE Id = :accId];
        return obj;
    }
}

In this example, the @HttpGet annotation allows the fetchAccount() method to be called when an HTTP GET request is made to the URL /services/apexrest/getAccountOnExternalIdtofetchsinglerecord/{accountId}. The method fetches the Account record based on the ID from the URL and returns the record in JSON format.

8) Can you explain how Salesforce handles multiple HTTP methods in a single Apex class, and what restriction exists regarding their usage?

In Salesforce, a single Apex class can expose multiple HTTP methods (GET, DELETE, POST, PUT, PATCH) through different annotated methods. However, each method can only be annotated with one of these HTTP methods—only one method per HTTP method type is allowed in a class. For example, you can have one method annotated with @HttpGet, another with @HttpPost, and so on, but you cannot have multiple methods using the same annotation (e.g., two @HttpGet methods in the same class). This ensures each HTTP action is uniquely handled by its corresponding method.

9) How can you use the @HttpGet annotation with parameters in the URL in Salesforce?

In Salesforce, the @HttpGet annotation can be used to define a web service that handles GET requests. If parameters are passed in the URL, you can use the params variable of the RestRequest class. The params variable returns a Map<String, String> that contains the parameters received by the request.

For example, if you want to create a web service that fetches a Contact record based on email and phone as parameters, you would use the following code:

@RestResource(urlMapping='/getContactFromEmailAndPhone/*')
global with sharing class getContactRecord {

    @Httpget
    global static Contact fetchContact() {
        Contact obj = new Contact();
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        
        Map<String, String> requestParam = req.params;
        String conEmail = requestParam.get('email');
        String conPhone = requestParam.get('phone');
        
        obj = [SELECT id, lastname, email, phone FROM Contact WHERE email = :conEmail AND phone = :conPhone];
        
        res.statusCode = 201;  // Modify HTTP status code to be returned to the external system
        return obj;
    }
}

This web service can be accessed using a URL like /services/apexrest/getContactFromEmailAndPhone?email=testemail2@gmail.com&phone=123. The parameters email and phone are retrieved from the URL and used to query the Contact record.

10) What are named credentials in Salesforce and how do they improve security when integrating with external services?

Named credentials in Salesforce provide a secure and declarative way to store and manage the authentication details (like usernames, passwords, or OAuth tokens) required for HTTP callouts to external systems. They allow developers to specify the endpoint URL and authentication parameters in one definition, simplifying the setup of authenticated callouts. Named credentials eliminate the need for remote site settings and ensure credentials are stored encrypted, enhancing security. They also make maintaining integrations easier—if an endpoint URL changes, only the named credential needs to be updated, and all related callouts remain functional without modifying the Apex code.

Gain a deep understanding of Salesforce integration, from creating and configuring Connected Apps to mastering advanced topics like OAuth flows, SAML-based Single Sign-On, and Streaming APIs. Our PDF course combines practical examples, real-time scenarios, and integration patterns to equip professionals with the skills needed to streamline processes and enhance productivity. Tailored for those with 2–8 years of experience, it’s your guide to unlocking seamless connectivity between Salesforce and other systems.

Link to course : Mastering Salesforce Integration