Salesforce CRM Basic Interview Questions

Table Of Contents
- Visualforce Basic Questions
- Apex fundamentals
- Batch Apex and Schedule apex questions.
- Schedule Apex
- Triggers
- WebServices
As someone diving into the world of Salesforce CRM, you’re likely aware of its immense popularity as a leading customer relationship management tool. But are you prepared to tackle the basic Salesforce CRM interview questions that could make or break your next opportunity? These questions often explore your understanding of essential concepts like managing accounts, contacts, leads, opportunities, and workflows. You might also face queries about Salesforce objects, data management, and the platform’s architecture. Interviewers aim to assess not just your knowledge but your ability to apply these foundational concepts to real-world scenarios.
In this guide, I’ve curated a list of Salesforce CRM basic interview questions that will help you prepare effectively and confidently. These questions aren’t just about testing what you know—they’re about equipping you with the ability to explain and apply your skills. Whether you’re just starting or need a quick refresher, this content will walk you through key topics with practical examples and clear explanations. With this preparation, you’ll be ready to stand out, impress interviewers, and take the next step in your Salesforce career.
Join our FREE demo at CRS Info Solutions to launch your Salesforce training in Hyderabad with our beginner-friendly online course. Benefit from expert instructors in live, interactive sessions covering Admin, Developer, and LWC modules, all aimed at interview preparation and certification. Seize this opportunity to enhance your skills and advance your career!
I. Visualforce Basic Questions
1. What is View State in Visualforce?
The View State in Visualforce is a mechanism that maintains the state of the page between the server and the client during a user’s session. It stores data in the form of objects, variables, and components used in the page. The platform encodes this state and sends it back to the server with every request. This helps Salesforce rebuild the page context without having to fetch everything from the database again. However, it also means larger pages may lead to increased View State size, impacting performance.
From my experience, understanding and optimizing View State is crucial when designing scalable Visualforce pages. For example, I avoid binding large data sets directly to the page and instead use pagination to reduce its size. Keeping View State size under 135 KB ensures the application runs efficiently. Additionally, using transient
variables for temporary data is an excellent way to minimize unnecessary state storage.
To manage View State, I often use transient
variables for temporary data that doesn’t need to persist between requests. For example:
public class SampleController {
public String persistentVar { get; set; }
@Transient
public String temporaryVar { get; set; }
}
This ensures temporaryVar
is excluded from the View State, optimizing performance. Additionally, limiting bound data and enabling pagination for large datasets also help minimize View State size.
2. Which API is used to design Visualforce pages?
The Metadata API is primarily used to design and manage Visualforce pages, as it allows us to interact programmatically with the Salesforce metadata. It helps create, update, or delete Visualforce pages and components. This API is essential for managing customizations and deploying Visualforce assets across different environments.
I’ve also utilized the Tooling API when working on advanced development tasks, such as debugging or building interactive UIs. For instance, the Tooling API allows easier access to the structure of Apex classes, Visualforce pages, and components. Understanding these APIs has helped me automate many deployment and customization processes in Salesforce projects.
3. What is the difference between actionSupport and actionFunction?
The key difference between actionSupport and actionFunction lies in how they enable AJAX functionality in Visualforce pages. actionSupport allows us to bind an AJAX request to a specific component’s event, like onclick
or onchange
. For example, you can use actionSupport to refresh a portion of the page when a user selects a dropdown value.
actionSupport binds AJAX functionality to a component’s specific event, like onclick
or onchange
. For example, in a dropdown menu, using actionSupport allows dynamic reloading of a related dropdown without refreshing the page:
<apex:selectList value={!selectedValue}" size="1">
<apex:selectOptions value="{!options}" />
<apex:actionSupport event="onchange" action="{!updateRelatedList}" rerender="relatedDropdown" />
</apex:selectList>
<apex:outputPanel id="relatedDropdown">{!relatedOptions}</apex:outputPanel>
actionFunction, on the other hand, defines a callable JavaScript function to invoke an AJAX request. Here’s an example:
<apex:actionFunction name="callServer" action="{!serverAction}" rerender="outputPanel" />
<button onclick="callServer();">Click Me</button>
<apex:outputPanel id="outputPanel">{!responseMessage}</apex:outputPanel>
I use actionFunction when I need explicit JavaScript control over server interactions.
See also: Salesforce Pardot Interview Questions
4. What is actionRegion?
The actionRegion tag in Visualforce is a way to limit the scope of data sent to the server during an AJAX request. By enclosing components within an actionRegion, I ensure that only their values are submitted when an AJAX call is triggered. This is particularly useful when working with large forms, as it minimizes data transfer and speeds up server processing.
I’ve often used actionRegion to optimize multi-step forms or complex UIs. For example, if a page has multiple sections, each with its own submit functionality, wrapping each section in its own actionRegion ensures that only the relevant section’s data is sent during submission. This practice enhances performance and prevents unintended side effects caused by irrelevant data processing.
5. What is the difference between insert and include?
The apex:insert and apex:include tags serve different purposes in Visualforce pages. Insert is used for embedding templates or standard components defined elsewhere, ensuring reusability and consistent UI. It’s especially helpful for headers or footers that are shared across multiple pages.
On the other hand, include pulls an external Visualforce page into the current page. This is useful for integrating complex components that require their logic. For instance, I’ve used include to embed custom charts or forms built in separate Visualforce pages, enabling modular design. Understanding these differences has helped me maintain cleaner, more modular codebases in large projects.
The apex:insert tag embeds templates, making it a useful tool for consistent headers, footers, or sidebars across multiple pages:
<apex:insert name="header" />
<apex:page>Page Content Here</apex:page>
<apex:insert name="footer" />
The apex:include tag includes external Visualforce pages into the current one, such as for embedding modular functionality:
<apex:include pageName="MySubPage" />
I use include to integrate reusable components, like forms or charts, into a parent page.
6. What is the difference between related List, enhanced List, and detail?
Related lists, enhanced lists, and detail views are different ways to display data in Salesforce. Related lists show associated records in a simple, tabular format on a parent record page. For example, an Account page displays related Contacts or Opportunities using related lists. These lists provide a quick overview but have limited interactivity.
In contrast, enhanced lists allow inline editing and dynamic filtering, providing a more interactive experience. They are commonly used in list views to manage large data sets efficiently. The detail view, on the other hand, focuses on a single record’s full details, such as fields and metadata. I use these views based on the requirements for interactivity or detailed record exploration.
7. What is the difference between controller and extension?
The controller is the backbone of a Visualforce page, managing its logic and data binding. A custom controller is a completely standalone class that handles every aspect of page behavior, including querying data and performing actions like save or update.
An extension, however, is used to extend the functionality of a standard or custom controller. For instance, I’ve created extensions to add specific methods or override existing behaviors without rewriting the whole controller. This modularity allows for cleaner, more maintainable code and enables reuse of existing logic.
See also: Salesforce Javascript Developer 1 Practice Exam Questions
8. What is Ajax? Have you used it? If so, tell the scenario?
AJAX (Asynchronous JavaScript and XML) enables partial page updates without refreshing the entire page. In Salesforce, I’ve used AJAX frequently in Visualforce pages to create dynamic and responsive interfaces.
One example is a dropdown menu that populates based on another field’s value. Using actionSupport with AJAX, I’ve made the second dropdown load dynamically without a page refresh. This approach improves user experience and ensures seamless data interaction.
9. What is jQuery? Where have you used it?
jQuery is a fast, lightweight JavaScript library used to simplify DOM manipulation, event handling, and AJAX calls. I’ve often incorporated jQuery in Salesforce for customizing UI interactions, such as creating modal popups or enhancing form validations.
In one project, I used jQuery to implement drag-and-drop functionality on a custom dashboard built with Visualforce. Its compatibility with different browsers and simplicity in writing scripts makes it a powerful tool for enriching Salesforce applications.
10. What is S-Controls?
S-Controls were a legacy Salesforce feature used to build custom user interfaces and interactions before Visualforce became standard. They relied on HTML, JavaScript, and CSS to create lightweight, dynamic components embedded within Salesforce pages.
Although now deprecated, I’ve seen S-Controls in older Salesforce implementations where they managed tasks like custom validations or embedding third-party widgets. Understanding their limitations and evolution helps in transitioning older codebases to modern standards using Visualforce or Lightning.
11. What is the use of Static Resource in Visualforce?
Static Resources in Visualforce allow us to upload and manage files like images, JavaScript, CSS, and other assets for use in Visualforce pages. These resources are stored in Salesforce and can be accessed using the $Resource
global variable. By leveraging Static Resources, I ensure consistent delivery of assets across pages without relying on external hosting.
For example, I once used Static Resources to include a custom CSS file for styling a Visualforce page. I uploaded the CSS file to Salesforce and referenced it in the page using <apex:stylesheet value="{!$Resource.CustomCSS}"/>
. This approach ensures faster load times and better resource management within the Salesforce ecosystem.
Explanation: This snippet demonstrates how to use Static Resources to style a Visualforce page. The uploaded CSS file is stored in Salesforce and referenced using the $Resource
variable in the <apex:stylesheet>
tag. This eliminates external dependencies, ensuring faster page rendering and consistent design.
12. Can I pass parameters from Visualforce page to an Apex method?
Yes, I can pass parameters from a Visualforce page to an Apex method. This is typically done using apex:param, which allows data to be sent along with an action. The parameter is then accessed in the Apex method using its bound variable.
For example, I’ve implemented a scenario where a button click passes a record ID to the Apex controller. Here’s the code:
<apex:commandButton action="{!processRecord}" value="Submit">
<apex:param name="recordId" value="{!record.Id}" assignTo="{!selectedRecordId}" />
</apex:commandButton>
Explanation: This code uses <apex:param>
to pass the record.Id
value from the Visualforce page to the controller’s selectedRecordId
variable. The processRecord
method processes this ID to perform actions like updates or queries dynamically.
13. How do you refer to the current page ID?
In Visualforce, I use the $CurrentPage
global variable to access details about the current page. To get the page’s ID, I retrieve it from the query parameters.
For instance, if I need the current record’s ID, I use the following code in the Apex controller:
String recordId = ApexPages.currentPage().getParameters().get('id');
Explanation: This snippet fetches the current page’s id
parameter using ApexPages.currentPage().getParameters().get()
. The retrieved recordId
can be used to query the record or perform other context-specific actions.
See also: Deloitte Salesforce Developer Interview Questions
14. Tell me something about $Action.
The $Action global variable provides access to predefined URLs for standard Salesforce actions like View, Edit, or Delete for a record. These URLs can be used to create hyperlinks or buttons in a Visualforce page.
For example, I’ve used $Action.Account.View
to navigate users directly to the Account detail page:
<apex:outputLink value="{!URLFOR($Action.Account.View, account.Id)}">View Account</apex:outputLink>
Explanation: The $Action.Account.View
generates a URL for the account’s detail page. The <apex:outputLink>
tag creates a clickable link, enabling seamless navigation for users without writing manual URLs.
15. How do you embed Google Maps in Visualforce?
To embed Google Maps in a Visualforce page, I use the Google Maps API and integrate it with Visualforce. By embedding an <iframe>
or using JavaScript, I can display a map with custom markers.
For instance, here’s a simple way I’ve done this:
<apex:page>
<iframe src="https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q=Salesforce+HQ"
width="600" height="450" style="border:0;" allowfullscreen=""></iframe>
</apex:page>
Explanation: The <iframe>
tag embeds Google Maps using the Maps API. The src
URL includes the API key and query parameter for the location, rendering the map on the Visualforce page dynamically.
16. What are custom components?
Custom components in Visualforce are reusable UI building blocks that encapsulate logic and markup. They allow me to design modular and maintainable pages by reusing components across multiple Visualforce pages.
For example, I’ve created a custom component for displaying a formatted record summary. This component receives record details as input and outputs the UI, making it easy to include on different pages with minimal effort.
Explanation: Custom components modularize the design by encapsulating functionality and structure. They reduce duplication and enhance maintainability, allowing developers to reuse them across multiple Visualforce pages.
17. How do you make a Visualforce page available for Salesforce1?
To make a Visualforce page accessible in Salesforce1, I ensure the page is mobile-optimized and marked as Available for Salesforce mobile apps
. This is configured under the Visualforce Page Settings in the setup menu.
Additionally, I follow best practices like using responsive designs and Lightning Stylesheets. For instance, I use <apex:page lightningStyleSheets="true">
to match the Salesforce1 interface. I’ve also leveraged Salesforce1 action buttons to provide quick access to Visualforce pages in mobile apps.
Explanation: The lightningStyleSheets
attribute ensures Visualforce pages adopt Salesforce1’s responsive styling. Marking the page as available for mobile apps integrates it seamlessly into Salesforce1.
See also: How to Optimize General Ledger Management in Salesforce?
18. How to use Sforce connection?
The Sforce connection refers to using Salesforce APIs, like SOAP or REST, to interact programmatically with Salesforce data. This is commonly used in Visualforce to fetch or manipulate data from external systems.
For example, I’ve used the Sforce SOAP API for querying data dynamically:
var sforceClient = new Sforce.Connection();
var queryResult = sforceClient.query("SELECT Name FROM Account");
console.log(queryResult);
Explanation: This JavaScript snippet establishes a connection to Salesforce using the Sforce SOAP API. The query()
method retrieves account names and logs the results for further processing.
19. What is a custom component?
A custom component is a self-contained block of Visualforce markup and logic that I can reuse across multiple pages. It simplifies page development by modularizing commonly used UI elements.
For example, I once created a custom component for rendering a list of records with sorting functionality. By reusing this component, I saved significant time during development and ensured consistent behavior across different pages.
Explanation: Custom components abstract functionality and styling, enabling developers to create and reuse a standardized UI for repeated features. This saves development time and ensures uniformity across applications.
20. How to implement autoLookup and query from Visualforce pages?
To implement autoLookup and dynamic querying in Visualforce, I combine AJAX with Apex and SOQL. This enables real-time data suggestions based on user input.
For example, I implemented an account name lookup using the following steps:
- A text box triggers an actionFunction on
keyup
. - The actionFunction calls an Apex method to fetch matching records.
- The returned results populate a dropdown dynamically.
Here’s a snippet of the approach:
<apex:inputText id="accountName" value="{!searchTerm}" onkeyup="searchRecords()"/>
<apex:actionFunction name="searchRecords" action="{!lookupAccounts}" reRender="results"/>
<apex:outputPanel id="results">
<apex:repeat value="{!accounts}" var="acc">
{!acc.Name}
</apex:repeat>
</apex:outputPanel>
Explanation: The <apex:inputText>
captures user input for the lookup. The actionFunction
calls the lookupAccounts
Apex method to fetch relevant accounts using SOQL. The outputPanel
displays the filtered results in real time.
II. Apex fundamentals
1. What is Apex?
Apex is a strongly-typed, object-oriented programming language developed by Salesforce. It allows developers to write custom business logic, such as triggers, batch processes, and web services, on the Salesforce platform. It is executed in a multitenant environment and tightly integrated with the Salesforce database. Apex supports database manipulation with DML operations and complex logic with its rich set of features. I often use Apex to create triggers for automating tasks like sending emails or updating related records. Additionally, it supports various features such as exception handling, custom classes, and REST services, making it powerful for extending Salesforce functionality.
2. What API is used in Apex?
Apex primarily interacts with Salesforce through its built-in SOAP and REST APIs. These APIs allow communication with external systems or within Salesforce components. For example, the SOAP API is used for complex integrations requiring metadata handling, while the REST API provides lightweight, HTTP-based interaction. In addition, Apex provides other APIs like the Database Class, which enables CRUD operations, and the Chatter API, which supports social interactions within Salesforce. I use these APIs in various scenarios, such as integrating Salesforce with an external CRM or retrieving data in real time for custom components.
3. What are the access modifiers in Apex?
Apex provides the following access modifiers to control the visibility of classes, methods, and variables:
- public: Accessible across all namespaces within Salesforce.
- private: Accessible only within the class where it is defined.
- protected: Accessible within the class and any subclass, including those in other namespaces.
- global: Accessible across all Apex code and even external systems.
- default (no modifier): Behaves like private but without explicit declaration.
For example, when defining utility methods intended for reuse, I mark them as public
or global
. Conversely, internal helper functions stay private
. This approach ensures encapsulation and minimizes unintended access.
4. What is the difference between With Sharing and Without Sharing?
With Sharing and Without Sharing are Apex class modifiers used to control record-level access.
- With Sharing enforces the current user’s sharing rules, meaning the class will respect the user’s visibility and permissions.
- Without Sharing runs the class with system-level permissions, bypassing sharing rules.
I use “With Sharing” for components requiring data visibility based on user roles, such as account lists. Conversely, “Without Sharing” is ideal for system-level processes like scheduled batch jobs.
5. What is a constructor?
A constructor is a special method in Apex that initializes a class when an object is created. It shares the class name and runs automatically during object creation. Constructors can be overloaded with multiple signatures for different initialization scenarios. For example, I use constructors in Apex controllers to initialize variables or retrieve data for a Visualforce page. Here’s a sample constructor for an account controller:
public class AccountController {
public AccountController() {
accountList = [SELECT Id, Name FROM Account LIMIT 10];
}
}
This initializes the accountList variable with a query fetching the first ten accounts. Constructors simplify setup and reduce redundant code.
6. What is the use of static variables?
Static variables are shared across all instances of a class and retain their values for the lifetime of the Apex transaction. They are ideal for storing data or state that must persist across method calls or components. For instance, I use static variables to cache query results or enforce limits, such as tracking the number of SOQL queries executed in a batch process. However, static variables are not persisted between transactions, which limits their use in asynchronous processes like future methods. By centralizing reusable data, static variables improve efficiency and code readability.
7. What are reference variables in Apex?
Reference variables in Apex store the memory address of an object rather than the object itself. This allows multiple variables to point to the same data, enabling shared updates and avoiding redundant object creation. For example, when I pass a custom object as a parameter to a method, the method modifies the same object rather than creating a copy. This behavior is useful in scenarios requiring consistency across multiple operations, such as updating related records within a trigger. Reference variables streamline operations by reducing memory usage and execution time.
See also: Capgemini Salesforce Developer Interview Questions
8. What are SObjects?
SObjects are Salesforce objects that represent database tables, such as Account, Contact, or custom objects. They serve as the backbone for database operations, enabling developers to insert, update, and query data. Apex provides a generic SObject
class and specific classes like Account
for working with Salesforce data. I frequently use SObjects to retrieve data with SOQL or DML statements. For example, the code Account acc = new Account(Name='Test');
creates a new Account record. SObjects provide a flexible and efficient way to manipulate Salesforce data programmatically.
9. What is the difference between List and Set?
Lists and Sets are collection types in Apex with distinct characteristics:
- A List maintains an ordered collection of elements that can contain duplicates. It is suitable for scenarios like maintaining a sequence of steps or grouping related records.
- A Set is an unordered collection that ensures unique elements, making it ideal for checking membership or removing duplicates.
For instance, I use Lists when I need ordered queries or pagination, and Sets when I handle unique user inputs for filters. Here’s an example:
List<String> names = new List<String>{'John', 'Jane', 'John'};
Set<String> uniqueNames = new Set<String>(names);
In this example, the Set removes duplicates, leaving only unique names. Lists and Sets complement each other in handling diverse data requirements.
10. What is Map in Apex?
A Map is a collection type in Apex that associates keys with values, allowing efficient data retrieval. It is particularly useful for scenarios where I need to store and access data based on unique identifiers. For example, I use Maps to retrieve records by their IDs without running additional queries. Here’s a sample use case:
Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Name FROM Account]);
This Map stores accounts with their IDs as keys, enabling efficient retrieval like accountMap.get(recordId)
. By leveraging Maps, I streamline operations requiring quick lookups and associations.
11. Can we have duplicate Keys in Map?
No, we cannot have duplicate keys in a Map in Apex. Each key in a Map is unique and can only appear once. If I try to insert a new key-value pair with a key that already exists, the old value for that key will be overwritten by the new value. For example, in the following code:
Map<String, String> myMap = new Map<String, String>();
myMap.put('A', 'Apple');
myMap.put('A', 'Avocado');
The value for the key 'A'
will be updated from 'Apple'
to 'Avocado'
. The Map only keeps the most recent value for each unique key. This behavior is crucial for ensuring data consistency and avoiding redundancy in key-value pairs.
12. How many objects can we store in a List?
In Apex, the number of objects we can store in a List depends on the governor limits imposed by Salesforce. Salesforce has a limit of 10 million records for List storage per transaction. However, there are other limits like heap size, which is 6 MB for synchronous operations and 12 MB for asynchronous operations. For example, if I’m inserting large numbers of records, I need to be mindful of heap size to avoid hitting the governor limit. Here’s an example:
List<Account> accountList = new List<Account>();
for(Integer i = 0; i < 2000; i++) {
accountList.add(new Account(Name='Account ' + i));
}
insert accountList;
In this case, even though the List holds thousands of records, I must ensure it does not exceed heap size limits during transactions.
13. What are setter and getter methods?
Setter and getter methods in Apex are used to control access to variables, especially in Visualforce controllers. The getter method is used to retrieve the value of a private or protected variable, while the setter method is used to set or update its value. For example, a getter for an Account object might look like this:
public class MyController {
private Account acc;
public Account getAcc() {
return acc;
}
public void setAcc(Account acc) {
this.acc = acc;
}
}
Here, the getter method getAcc()
returns the value of the acc
variable, and the setter setAcc()
allows for modification of that variable. These methods provide encapsulation and allow for better control over how data is accessed or modified.
14. How do you refer to current page id in Apex?
In Apex, I can refer to the current page ID using the ApexPages.currentPage()
method, which returns the current page reference. To get the page ID from the URL, I can use the getParameters()
method on the page reference object. Here’s an example:
String currentPageId = ApexPages.currentPage().getParameters().get('id');
In this case, the code extracts the 'id'
parameter from the current page URL. This method is particularly useful when working with Visualforce pages to capture dynamic URL parameters.
See also: Salesforce Approval Process Interview
15. How do you invoke standard actions in Apex class?
To invoke standard actions in Apex, I can use the PageReference
object to reference the standard page and invoke its actions. Standard actions like Edit, Delete, or View can be triggered through the ApexPages.addMessage()
method or by calling the PageReference.getParameters()
to set the action. For example, I use the following code to invoke the edit action for an Account:
PageReference editPage = new PageReference('/' + recordId + '/e');
editPage.setRedirect(true);
return editPage;
In this example, the URL '/e'
triggers the standard edit page for the record with the specified ID. Standard actions are powerful when creating custom workflows or extending Salesforce functionality.
16. What is page reference?
A PageReference in Apex represents a Visualforce page or a standard Salesforce page. It is used to refer to a page in order to redirect users, pass parameters, or invoke standard actions. For instance, I use a PageReference when redirecting a user to a specific Visualforce page after a successful record creation. Here’s an example:
PageReference myPage = new PageReference('/apex/MyCustomPage');
myPage.setRedirect(true);
return myPage;
This code creates a PageReference to a custom Visualforce page and redirects the user to that page. The PageReference object helps with page navigation and action handling in Apex controllers.
17. How do you pass parameters from one Apex class to another?
To pass parameters between Apex classes, I typically use public properties or constructor parameters. For example, I can pass an Account ID from one class to another by setting it as a parameter in the constructor or through a setter method. Here’s an example of passing parameters via a constructor:
public class FirstClass {
public String accountId;
public FirstClass(String accId) {
accountId = accId;
}
}
I instantiate FirstClass from another Apex class and pass the parameter like this:
FirstClass fc = new FirstClass('001xxxxxxxxxxxx');
This ensures that data is passed and accessible across different classes in the same transaction.
18. What is virtual class?
A virtual class in Apex is a class that can be extended or inherited by other classes. It is designed to allow for inheritance, providing a base functionality for other classes to build upon. A virtual class is declared using the virtual
keyword. For instance, I can create a virtual class for generic operations like logging, and other classes can extend it to implement specific details:
public virtual class BaseLogger {
public virtual void log(String message) {
// log message
}
}
In this case, the BaseLogger
class can be extended by other classes to provide specific logging implementations. The virtual class is important for creating reusable, extendable code in Apex.
19. What is abstract class?
An abstract class in Apex is a class that cannot be instantiated directly but must be subclassed. It may contain abstract methods (without implementation) that must be implemented by the derived class. The purpose of an abstract class is to define a common interface or structure for its subclasses. For example:
public abstract class Animal {
public abstract void makeSound();
}
In this case, the Animal
class cannot be instantiated on its own, but any subclass, like Dog
or Cat
, must implement the makeSound
method. Abstract classes are used to define common functionality and enforce structure in a codebase.
20. What is overloading?
Overloading in Apex refers to defining multiple methods with the same name but different parameter types or numbers of parameters. This allows a class to perform similar operations using the same method name, depending on the input parameters. For example, I can create an overloaded method for calculating the area of different shapes:
public class ShapeCalculator {
public Double calculateArea(Double radius) {
return Math.PI * radius * radius;
}
public Double calculateArea(Double length, Double width) {
return length * width;
}
}
In this example, I overloaded the calculateArea
method to work with a single radius for circles and two parameters (length and width) for rectangles. Overloading provides flexibility and keeps the code clean.
21. What is overriding?
Overriding is when a subclass provides its own implementation of a method that is already defined in the base class. The method in the child class has the same name, return type, and parameters as the method in the parent class. Overriding is used to modify or extend the behavior of an inherited method. Here’s an example:
public class Animal {
public virtual void makeSound() {
System.debug('Animal makes sound');
}
}
public class Dog extends Animal {
public override void makeSound() {
System.debug('Bark');
}
}
In this example, the Dog
class overrides the makeSound
method of the Animal
class to provide a more specific implementation. Overriding is essential for dynamic polymorphism in object-oriented programming.
See also: Salesforce Apex Interview Questions
22. When we invoke a with-sharing method in a without-sharing class, how is the method executed?
If I invoke a with-sharing method inside a without-sharing class, the method will still execute with the sharing rules defined by the method, not the class. The sharing rules for the method will override the class-level sharing settings. For instance, if the method enforces sharing rules (via with sharing
), those rules will apply to the records in the method, regardless of the class’s without sharing
declaration. Here’s an example:
public with sharing class SharingClass {
public void methodWithSharing() {
// enforce sharing rules
}
}
public without sharing class NoSharingClass {
public void callMethod() {
SharingClass sc = new SharingClass();
sc.methodWithSharing();
}
}
In this case, methodWithSharing
still respects sharing rules even when invoked from NoSharingClass
.
23. Will the inner class inherit the sharing properties of the outer class?
No, inner classes in Apex do not inherit the sharing properties of the outer class. If the outer class is declared with sharing
, it does not automatically mean that the inner class will follow the same sharing rules. Each class, whether outer or inner, must explicitly declare its sharing settings (either with sharing
or without sharing
). Here’s an example:
public with sharing class OuterClass {
public class InnerClass {
// This inner class does not inherit the sharing properties of OuterClass
}
}
In this case, the InnerClass
does not inherit the with sharing
rule of the OuterClass
. Sharing rules for the inner class must be specified independently if needed.
24. Base class is declared as With Sharing and Derived class is declared as Without Sharing, what will happen?
When the base class is declared as with sharing and the derived class is declared as without sharing, the derived class‘s sharing settings will take precedence. This means that if I invoke a method from the derived class, it will execute without sharing, regardless of the base class’s with sharing
declaration. This behavior allows the derived class to bypass the sharing rules defined by the base class. Here’s an example:
public with sharing class BaseClass {
public void methodWithSharing() {
// enforces sharing rules
}
}
public without sharing class DerivedClass extends BaseClass {
public void methodWithoutSharing() {
// bypasses sharing rules
}
}
In this case, when I call methodWithSharing
in the DerivedClass
, it will execute without sharing.
25. Can I have a constructor with parameters in Apex?
Yes, I can have a constructor with parameters in Apex. A constructor in Apex is a special method used to initialize objects when they are created. A constructor can accept parameters that allow me to pass values during object creation, enabling more dynamic and flexible instantiations. For example:
public class MyClass {
public String name;
public MyClass(String name) {
this.name = name;
}
}
In this example, the MyClass
constructor accepts a String
parameter called name
and initializes the object’s name
property with that value. I can now create an instance of MyClass
and pass the name as a parameter:
MyClass obj = new MyClass('John Doe');
26. Dereferencing a Null Pointer Value Error?
Dereferencing a null pointer error occurs when I try to access a property or method of an object that has not been initialized (i.e., it is null). This can lead to runtime exceptions. To avoid this, I ensure that the object is properly initialized before accessing its properties or methods. For example:
Account acc;
System.debug(acc.Name); // Will cause a null pointer exception
In this case, since acc
is null, accessing its Name
property will throw a null pointer exception. To prevent this, I should check if the object is null first:
if (acc != null) {
System.debug(acc.Name);
}
This ensures the code only attempts to access acc.Name
if the acc
object is not null.
27. Variable is not available?
A “variable is not available” error typically occurs when I try to access a variable that is out of scope or not properly initialized. This might happen if a variable is declared within a method and I try to access it outside its scope, or if the variable is not instantiated before being used. For example:
public void myMethod() {
String myString; // Declared but not initialized
System.debug(myString); // Error: variable is not available
}
In this case, the variable myString
is declared but never initialized, leading to a “variable is not available” error. I should initialize the variable before using it:
String myString = 'Hello, World!';
System.debug(myString);
28. Too many records: ‘10001’
The “Too many records: ‘10001’” error occurs when an Apex operation attempts to process more than 10,000 records in a single transaction. Salesforce imposes this limit to protect system performance. To avoid this error, I can implement batching or pagination to process records in smaller chunks. For example, using a batch Apex class:
global class MyBatchClass implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([SELECT Id FROM Account LIMIT 10000]);
}
global void execute(Database.BatchableContext BC, List<Account> records) {
// Process records
}
global void finish(Database.BatchableContext BC) {
// Finalize processing
}
}
In this case, using batch Apex allows me to process a large number of records (up to 50 million) without exceeding the governor limits.
See also: Salesforce Developer Interview Questions for 8 years Experience
III. Batch Apex and Schedule apex questions.
1. What are the SOQL limitations in Apex?
In Apex, SOQL (Salesforce Object Query Language) is limited by governor limits to ensure efficient processing. A single transaction can execute up to 100 SOQL queries, and the total number of rows retrieved must not exceed 50,000. Additionally, a single SOQL query cannot return more than 2,000 records in synchronous Apex. For queries involving child relationships, I must optimize joins to avoid exceeding limits.
2. What are transaction limits in Apex?
Apex enforces transaction limits to maintain system performance. Some key limits include:
- CPU time: Maximum of 10,000 milliseconds.
- Heap size: 6 MB for synchronous and 12 MB for asynchronous transactions.
- DML operations: Maximum of 150 operations per transaction.
- Callouts: Up to 100 HTTP callouts per transaction.
These limits ensure resource efficiency and scalability in Salesforce environments.
3. What is the need for Batch Apex?
Batch Apex is needed for handling large datasets that exceed transaction limits. Regular Apex cannot process more than 50,000 records in a single transaction, but Batch Apex can process up to 50 million records in smaller chunks, adhering to governor limits. It is particularly useful for scheduled data processing, cleanup tasks, and integrations.
4. What is Database.Batchable interface?
The Database.Batchable interface in Apex allows developers to create Batch Apex classes for processing large datasets efficiently. By implementing this interface, I can divide data into manageable chunks (or batches) and process them asynchronously. This interface provides three methods: start
, execute
, and finish
.
5. Define the methods in the Batchable interface?
The Batchable interface defines the following methods:
start
: Returns the data to be processed in the form of aDatabase.QueryLocator
or anIterable
.execute
: Processes each batch of data.finish
: Executes post-processing logic, such as sending notifications or chaining another batch job.
These methods enable structured and scalable data processing.
6. What is the purpose of the Start method in Batch Apex?
The Start method in Batch Apex initializes the batch job and determines the scope of data to be processed. It must return either a Database.QueryLocator
for SOQL-based jobs or an Iterable
for custom collections. For example:
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator('SELECT Id FROM Account');
}
This ensures that only the required records are included in the batch job.
7. What is the Database.QueryLocator?
The Database.QueryLocator is a return type for the start
method in Batch Apex. It represents a SOQL query that can retrieve a large number of records (up to 50 million). It optimizes query execution and avoids heap size limitations by streaming data in batches.
8. What is the Iterable?
An Iterable is a collection of elements that can be iterated (looped) over. In Batch Apex, it can be used as an alternative to Database.QueryLocator
in the start
method. By implementing the Iterable
interface, I can customize the collection of records to process in the batch job.
9. How to define the custom Iterable?
To define a custom Iterable, I create a class that implements the Iterable
and Iterator
interfaces. For example:
global class CustomIterable implements Iterable<Account> {
global Iterator<Account> iterator() {
return new CustomIterator();
}
}
global class CustomIterator implements Iterator<Account> {
private List<Account> accounts = [SELECT Id FROM Account];
private Integer index = 0;
global Boolean hasNext() {
return index < accounts.size();
}
global Account next() {
return accounts[index++];
}
}
This custom iterable allows me to define specific logic for retrieving records in the batch job.
10. What is the use of the Execute method?
The Execute method processes each batch of data returned by the start
method. It contains the business logic for the batch operation. For example:
global void execute(Database.BatchableContext BC, List<Account> scope) {
for (Account acc : scope) {
acc.Status__c = 'Processed';
}
update scope;
}
In this example, the Execute
method updates the Status__c
field for each batch of Account
records. This method ensures the job is performed efficiently and adheres to governor limits.
See also: LWC Interview Questions for 5 years experience
11. How many times is the execute method called?
The execute method in Batch Apex is called once for each batch of records processed. The number of times it runs depends on the total number of records and the batch size specified. For example, if there are 1,000 records and the batch size is 200, the execute
method will run 5 times. Each call processes one chunk of the data efficiently, adhering to governor limits.
12. What is the scope of the execute method?
The scope of the execute method refers to the subset of records passed to it during each execution. The batch size, defined while calling the batch job (e.g., Database.executeBatch(batchClassInstance, batchSize)
), determines this scope. For instance, if the batch size is set to 100, the execute method will process 100 records at a time. This ensures controlled and efficient processing of data.
13. Can we call callouts from Batch Apex?
Yes, we can perform callouts in Batch Apex, but only in asynchronous transactions. To enable callouts, the class must implement the Database.AllowsCallouts
interface. The execute method can then include HTTP callouts, provided they adhere to Salesforce callout limits (e.g., a maximum of 100 callouts per transaction). This feature is especially useful for integrating external systems with Salesforce.
14. Can we call another batch apex from Batch Apex?
No, you cannot directly call one Batch Apex class from another batch within the same transaction. However, you can chain Batch Apex jobs using the finish
method. For example:
global void finish(Database.BatchableContext BC) {
Database.executeBatch(new NextBatchClass(), 200);
}
This approach allows sequential execution of batch processes.
15. How many callouts can we make in Batch Apex?
In Batch Apex, you can make up to 100 callouts per execute method call. If each batch processes 100 records, each callout must handle one record or fewer to stay within limits. Managing callouts in smaller scopes ensures compliance with Salesforce governor limits.
16. If you get a Callouts Governing Limits error, how do you rectify it?
To resolve a Callouts Governing Limits error, I can:
- Reduce the number of callouts per execute method.
- Consolidate multiple callouts into a single call to minimize requests.
- Adjust the batch size to reduce the total callouts in one transaction.
- Implement asynchronous processing, such as future methods or queueable Apex, to handle callouts separately.
17. Is Batch Apex a synchronous or asynchronous operation?
Batch Apex is an asynchronous operation. It processes large datasets in smaller chunks and executes in the background. This asynchronous nature allows me to bypass synchronous transaction limits, such as SOQL and DML limits, while ensuring the system’s stability and performance.
18. How do you synchronize Batch Apex?
To synchronize Batch Apex, I can use the finish method to chain another batch job. Alternatively, I can leverage Apex Scheduler to schedule batches at specific intervals. Synchronization ensures that one batch completes before the next begins. Using Apex Scheduler also provides control over timing and sequence.
19. How do you call Batch Apex from Batch Apex in earlier versions of API 26.0?
Before API version 26.0, chaining Batch Apex jobs was not natively supported. To achieve similar functionality, I used the System.scheduleBatch method to schedule a new batch job at the end of the current batch. For example:
global void finish(Database.BatchableContext BC) {
System.scheduleBatch(new NextBatchClass(), 1);
}
This workaround ensures smooth execution of dependent batch jobs.
20. What are the general errors/exceptions we may encounter when executing Batch Apex?
Common errors in Batch Apex include:
- Too many SOQL queries: Exceeding the SOQL query limit in a single transaction.
- Callout limits exceeded: More than 100 HTTP callouts in one transaction.
- Heap size exceeded: Allocating more memory than allowed.
- CPU time limit exceeded: The code runs longer than the allowed CPU time.
- DML statement limit exceeded: Performing more than 150 DML operations in a single transaction.
To mitigate these, I optimize queries, use bulk processing, and adhere to governor limits.
See also: Salesforce DevOps Interview Questions
21. What is the maximum size of the batch and minimum size of the batch?
The maximum batch size in Batch Apex is 2,000 records, and the minimum batch size is 1 record. When calling Database.executeBatch
, the batch size parameter determines how many records the execute method processes at a time. By default, if no size is specified, Salesforce uses a batch size of 200. Optimizing the batch size can help balance performance and governor limit constraints.
22. Tell some of the scenarios that you have developed using Batch Apex?
I have developed Batch Apex for scenarios such as mass updating records, recalculating values, and sending reminders. For example:
- Mass Data Processing: Updating the
Status
field on thousands ofCase
records based on a specific condition. - Integration Tasks: Synchronizing Salesforce data with external systems by making HTTP callouts in each batch.
- Scheduled Cleanup: Deleting inactive leads that haven’t been updated in over a year. These use cases highlight how Batch Apex manages large datasets efficiently.
23. What is Database.BatchableContext?
The Database.BatchableContext interface provides context about the currently executing batch job. It includes methods like getJobId
, which returns the unique identifier for the batch job. This information is useful for tracking and monitoring the progress of the job and chaining additional processes.
24. How to track the details of the current running Batch using BatchableContext?
To track details of the current running batch, I use the BatchableContext object. For instance, BC.getJobId()
retrieves the unique job ID, which I can query in the AsyncApexJob
object to get the batch’s status and progress. Example:
AsyncApexJob job = [SELECT Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :BC.getJobId()];
System.debug('Job Status: ' + job.Status);
This approach ensures real-time tracking of batch details.
25. How many batch jobs can be added to the queue?
Salesforce allows up to 5 active or queued batch jobs at a time per organization. However, completed or aborted jobs do not count towards this limit. If the limit is exceeded, Salesforce throws a LimitException
. To manage this, I monitor and prioritize batch jobs effectively.
26. What is Database.Stateful Interface?
The Database.Stateful interface allows a Batch Apex class to maintain state across transaction boundaries. Without this interface, variables in a batch class reset between transactions. By implementing it, I can preserve data like counts or logs during the execution of all batches. Example use case: tracking the total number of processed records.
27. What is Database.AllowCallouts?
The Database.AllowCallouts interface enables Batch Apex classes to make HTTP callouts during execution. This is crucial for integrating with external systems. For example, when processing batches, I can fetch external data using a REST API callout. Without this interface, callouts are not permitted in Batch Apex.
28. Why should we call Database.executeBatch() and future methods in Test.StartTest() and Test.StopTest()?
In test classes, I enclose Database.executeBatch and future methods within Test.startTest()
and Test.stopTest()
to simulate the asynchronous execution of these methods. This ensures proper validation and avoids governor limit violations during testing. Additionally, these blocks help isolate test-specific transactions for better control.
29. What is AsyncApexJob object?
The AsyncApexJob object represents an Apex job scheduled to run asynchronously, such as Batch Apex, Scheduled Apex, or Queueable Apex. It contains details like Status
, NumberOfErrors
, and TotalJobItems
. By querying this object, I can monitor and manage jobs in progress.
30. When is a BatchApexWorker record created?
A BatchApexWorker record is created each time the system processes a batch from a Batch Apex job. It represents an individual execution of the execute
method for that batch. This record is crucial for tracking and debugging specific batch executions within a job.
See also: Salesforce Admin Exam Guide 2024
IV. Schedule Apex
1. What is Schedule Apex?
Schedule Apex allows us to schedule the execution of Apex classes at a specific time. It is useful for automating repetitive tasks such as daily data updates, integration tasks, or cleanup operations. To use Schedule Apex, the class must implement the Schedulable
interface and include the execute
method.
2. How many ways can we schedule the batch apex?
We can schedule batch Apex in two ways:
- Using the Salesforce UI: Navigate to Setup > Apex Classes > Schedule Apex, and define the schedule details.
- Using the System.schedule method in Apex: This approach allows dynamic scheduling by specifying the job name, a cron expression, and the class.
3. What is Schedulable interface?
The Schedulable interface is an Apex interface that a class must implement to define scheduled jobs. It contains the execute(SchedulableContext SC)
method, which Salesforce calls at the scheduled time. This method defines the logic to execute when the job runs.
4. What is the order of execution?
The order of execution for Schedule Apex is as follows:
- The scheduler triggers the job based on the defined cron expression.
- The
execute
method runs the scheduled logic. - If the job involves Batch Apex, it executes as per the defined batch size.
- After completion, Salesforce logs the job details in the
AsyncApexJob
object.
5. How can we schedule the batch apex?
To schedule Batch Apex, I either use the Salesforce UI or write an Apex class that implements the Schedulable
interface. In the execute
method, I invoke the Batch Apex using Database.executeBatch
. For example:
global class MyScheduler implements Schedulable {
global void execute(SchedulableContext SC) {
Database.executeBatch(new MyBatchClass(), 200);
}
}
This ensures the batch runs automatically at the scheduled time.
6. How many schedule jobs can we schedule at a time?
Salesforce allows up to 100 active scheduled jobs per organization at any given time. This limit includes all scheduled jobs, whether they are Apex jobs or scheduled reports. Proper job management is essential to stay within this limit.
7. What is cronTrigger?
The cronTrigger object represents the schedule for a job in Salesforce. It stores details like the next scheduled run time, the cron expression, and job status. By querying this object, I can monitor or adjust scheduled jobs. For example:
CronTrigger ct = [SELECT NextFireTime FROM CronTrigger WHERE Id = :jobId];
System.debug('Next Fire Time: ' + ct.NextFireTime);
8. How to identify the job’s next schedule?
To identify the job’s next schedule, I query the CronTrigger object using the job ID. The NextFireTime
field specifies when the job will execute next. Example:
CronTrigger ct = [SELECT NextFireTime FROM CronTrigger WHERE Id = :jobId];
System.debug('Next scheduled time: ' + ct.NextFireTime);
This method ensures visibility into job scheduling.
9. What is the difference between Synchronous and Asynchronous jobs?
- Synchronous Jobs: These jobs run immediately and block the execution thread until completion. Examples include trigger execution or Apex code run in the developer console.
- Asynchronous Jobs: These jobs run in the background, allowing other operations to proceed. Examples include Batch Apex, Queueable Apex, and future methods.
10. How many future calls can we make in a day?
Salesforce enforces a governor limit of 250,000 future calls per 24 hours per organization. This limit ensures efficient resource utilization. To avoid exceeding it, I optimize logic and consider alternate asynchronous mechanisms like Queueable Apex or Batch Apex when necessary.
11. What is the difference between manual schedule and Apex schedule?
In manual scheduling, I use the Salesforce UI to set up scheduled jobs, such as scheduled reports or scheduled Apex classes. This method is straightforward but lacks flexibility for dynamic schedules. In contrast, Apex scheduling involves using the System.schedule
method in Apex code. This method allows more complex scheduling, such as programmatically adjusting job timing or triggering multiple jobs based on conditions.
12. What is the best scenario that you have designed using schedule Apex?
One of the best scenarios I worked on involved scheduling nightly data synchronization between Salesforce and an external system. I used Batch Apex combined with Schedule Apex to fetch updated data from the external system via API callouts. The Schedulable
interface ensured the process ran at 2 AM daily, minimizing user impact. This approach automated data updates, improved accuracy, and reduced manual workload.
13. How to invoke asynchronous calls?
I invoke asynchronous calls using mechanisms like Future methods, Queueable Apex, or Batch Apex. For example, in a Schedule Apex class, I often use future methods for callouts:
@future(callout=true)
public static void fetchData() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/data');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
}
Here, the @future
annotation ensures the method executes asynchronously, allowing seamless background operations.
14. Can we call synchronous callouts in Schedule Apex?
No, synchronous callouts cannot be executed directly in Schedule Apex because it runs in an asynchronous context. Instead, I use a future method or Queueable Apex to handle callouts. For example:
apexCopy code@future(callout=true)
public static void fetchData() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/data');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
}
This ensures compliance with Salesforce governor limits while performing external integrations.
15. What are the problems that you have encountered while using Schedule Apex?
I’ve faced several challenges while using Schedule Apex:
- Governor Limits: Exceeding limits, such as SOQL or DML operations, required optimizing the code or splitting tasks into smaller batches.
- Callout Restrictions: Since direct synchronous callouts aren’t allowed, I had to restructure logic using future or Queueable Apex for API integrations.
- Debugging Issues: Monitoring scheduled jobs can be difficult without proper logging. I addressed this by implementing detailed logs and querying the AsyncApexJob object for job statuses.
See also: Salesforce OWD Interview Questions and Answers
V. Triggers
1. What is trigger?
A trigger in Salesforce is an Apex script that executes automatically when a specific database event, such as insert
, update
, delete
, or undelete
, occurs on an object. Triggers enable me to add custom logic before or after these events. For instance, I can create a trigger to validate a record’s data or update related records when a change is made.
Triggers allow seamless automation, eliminating manual intervention for repetitive tasks. They provide a robust mechanism to ensure data integrity and implement business logic directly at the database level.
2. What are different types of Triggers in Salesforce?
Salesforce supports two types of triggers:
- Before Trigger: Executes before the record is saved to the database. I use this type to validate data or modify values before committing the record.
- After Trigger: Executes after the record is saved to the database. This type is useful when I need to perform operations dependent on the record ID, such as updating related records.
Both types can handle multiple events, including insert
, update
, delete
, and undelete
.
3. What are Trigger Context variables?
Trigger Context variables are predefined variables in Salesforce triggers that provide context about the database event. For example:
Trigger.new
: Contains new records duringinsert
orupdate
operations.Trigger.old
: Holds the original records duringupdate
ordelete
operations.Trigger.isInsert
: Indicates if the trigger was fired due to aninsert
event.
These variables allow me to write efficient, context-aware logic in triggers.
4. What is the difference between Trigger.New and Trigger.NewMap?
Trigger.new
is a list of new records in the trigger context, commonly used for iterating through records. On the other hand, Trigger.newMap
is a map where each key is the record ID, and the value is the corresponding record.
For example:
for (Account acc : Trigger.new) {
// Process each record
}
Account account = Trigger.newMap.get(someId); // Access by ID
Trigger.new
is simpler for looping, while Trigger.newMap
is better for accessing records by their IDs.
5. What is the difference between Trigger.New and Trigger.Old?
Trigger.new
holds the updated or inserted versions of records during insert
or update
events. Trigger.old
, however, holds the original records before the update or during the delete
operation. For example, in an update
trigger, I use Trigger.old
to compare old and new values to identify changes.
for (Integer i = 0; i < Trigger.new.size(); i++) {
if (Trigger.new[i].Name != Trigger.old[i].Name) {
// Name field changed
}
}
6. What is the difference between Trigger.New and Trigger.Old in update Trigger?
In an update
trigger, Trigger.new
contains the updated records, while Trigger.old
contains the original values of those records. For instance, if I need to track field changes, I compare the values in both lists. This helps me identify modifications and implement logic based on the changes.
7. Can we call the Batch Apex from the Trigger?
Yes, I can call Batch Apex from a trigger, but it should be implemented with care to avoid exceeding governor limits. The Database.executeBatch
method allows me to process large datasets from a trigger. However, best practices recommend limiting the frequency of batch calls from triggers to prevent performance issues.
8. What are the problems you have encountered when calling Batch Apex from the Trigger?
Calling Batch Apex from triggers can lead to several issues:
- Recursive Calls: Triggers may re-fire when batch jobs perform DML operations, causing unwanted recursion.
- Governor Limits: Exceeding limits like maximum batch job executions in a day.
- Performance Impact: Processing a batch from triggers may delay operations.
I mitigate these issues by using static variables to prevent recursion and by carefully managing trigger logic.
9. Can we call the callouts from triggers?
Direct callouts are not allowed in triggers because they run in a synchronous context. However, I can make callouts indirectly by using future methods or Queueable Apex, which execute asynchronously. For example:
@future(callout=true)
public static void makeCallout() {
// HTTP callout logic
}
10. What are the problems that you encountered while calling Apex callouts in triggers?
Key challenges include:
- Callout Restrictions: Synchronous triggers cannot perform callouts directly.
- Governor Limits: Ensuring that the number of callouts and execution time remain within limits.
- Delayed Execution: Using asynchronous methods like future methods can introduce delays, impacting dependent processes.
11. What is the recursive trigger?
A recursive trigger occurs when a trigger calls itself repeatedly due to an unintended loop. For instance, if a trigger performs a DML operation that causes the same trigger to fire again, it creates a recursive loop. This can lead to governor limit violations or performance issues.
12. What is bulkifying triggers?
Bulkifying triggers means writing trigger logic to handle multiple records at once, rather than processing each record individually. For example, instead of querying or performing DML operations inside a loop, I use collections to handle bulk data efficiently.
List<Account> accountsToUpdate = new List<Account>();
for (Account acc : Trigger.new) {
acc.Name = 'Updated Name';
accountsToUpdate.add(acc);
}
update accountsToUpdate;
13. What is the use of future methods in triggers?
I use future methods in triggers for tasks like making callouts or performing asynchronous operations. Since triggers run synchronously, they can’t directly make callouts. Future methods enable me to delegate these tasks asynchronously, ensuring smoother execution without governor limit violations.
14. What is the order of executing the trigger in Apex?
The execution order for triggers in Apex is as follows:
- Before Triggers
- Validation Rules
- After Triggers
- Assignment Rules
- Auto-Response Rules
- Workflow Rules
- Process Builder
- Escalation Rules
- Roll-up Summary Field Calculations
15. What is a trigger handler?
A trigger handler is a design pattern where the logic of a trigger is moved to an Apex class. This ensures modularity, easier debugging, and better maintenance. For instance, the trigger only invokes methods in the handler class, keeping the trigger itself clean and concise.
16. How do you avoid recursive triggers?
To avoid recursive triggers, I use a static Boolean variable in a helper class. This variable tracks whether the trigger has already been executed. If it’s true, the trigger logic doesn’t run again.
public class TriggerHelper {
public static Boolean isTriggerExecuted = false;
}
17. How many triggers can we define on an object?
Salesforce allows us to define multiple triggers on a single object. However, it’s a best practice to consolidate trigger logic into a single trigger to maintain clarity and avoid conflicts between triggers.
18. Can we define two triggers with the same event on a single object?
Yes, Salesforce permits defining two triggers for the same event on an object. However, the execution order of these triggers is not guaranteed, which can lead to unpredictable behavior. I prefer using a single trigger to handle all events for better control.
19. Tell me some scenarios where you have written the triggers?
- Automatically updating a related object when a record is inserted or updated.
- Creating tasks when a lead’s status changes to “Qualified.”
- Preventing deletion of important records by adding custom validation logic in
before delete
triggers.
20. What is the best scenario that you have developed on triggers?
One of my best scenarios was creating a trigger to maintain historical data in a custom object. The trigger captured changes to critical fields on the Account object and logged the previous and new values in a related History object.
21. How many times will a workflow field update be called in triggers?
A workflow field update will cause a trigger to execute again if it updates a field that the trigger logic depends on. The trigger can fire up to twice per transaction due to workflow updates.
22. When are the roll-up summary fields calculated?
Roll-up summary fields are recalculated after the following events:
- On a parent object, after a child record is inserted, updated, or deleted.
- When a field that the roll-up summary depends on changes.
These calculations occur automatically and asynchronously to maintain data consistency.
VI. WebServices:
1. What is the difference between HTTP 1.0 and HTTP 2.0?
In my experience, HTTP 1.0 and HTTP 2.0 differ primarily in how they handle requests and data transmission. HTTP 1.0 establishes a separate connection for each request-response cycle. This makes it slower, especially when dealing with multiple resources like images or scripts. HTTP 2.0, on the other hand, uses a single connection and multiplexing, allowing multiple requests and responses to happen simultaneously, which significantly improves performance.
Another key difference is that HTTP 1.0 does not support server push, while HTTP 2.0 can proactively send resources to the client without waiting for requests. For example, in HTTP 2.0, the server can push a CSS file immediately after sending an HTML file, reducing load times.
// HTTP 1.0 - Sequential Requests
GET /index.html HTTP/1.0
Connection: close
// HTTP 2.0 - Multiplexed Requests
GET /index.html HTTP/2
GET /style.css HTTP/2
// Both are sent over a single connection
In my projects, I’ve found HTTP 2.0 to be highly efficient when optimizing website speed and user experience.
2. Difference between REST API and SOAP API?
From my experience, the main difference is that REST APIs are lightweight and use simple protocols like HTTP for communication. REST is stateless, making it faster and easier to implement, especially when working with JSON. On the other hand, SOAP APIs are more structured and rely on XML. SOAP is ideal for enterprise-level security and transactional support but can be slower due to its complexity.
For instance, a REST API for fetching user data might look like this:
GET /users/123
Host: example.com
Authorization: Bearer token123
While a SOAP API would involve a more detailed XML request:
<soap:Envelope>
<soap:Body>
<GetUserRequest>
<UserId>123</UserId>
</GetUserRequest>
</soap:Body>
</soap:Envelope>
In my opinion, I would recommend REST for modern, lightweight applications and SOAP for robust systems requiring strict contracts and security.
See also: Accenture LWC Interview Questions
Conclusion
Mastering Salesforce CRM Basic Interview Questions is essential for anyone looking to build a solid foundation in this powerful platform. It’s not just about answering questions; it’s about understanding how Salesforce CRM can transform business operations, enhance customer relationships, and drive growth. By confidently addressing these fundamental questions, you not only prove your knowledge of Salesforce but also demonstrate your potential to thrive in a CRM-driven environment.
For those looking to stand out, a strong command of the Salesforce CRM Basic Interview Questions is key to unlocking more advanced concepts and opportunities. These basics are your first step toward mastering automation, integration, and custom development within the Salesforce ecosystem. With the right preparation and a deep understanding of these foundational topics, you’ll be well on your way to excelling in interviews and becoming an invaluable asset to any organization leveraging Salesforce.
Why Salesforce Training in Hyderabad is Essential?
Hyderabad has emerged as a thriving tech city, attracting global corporations and fostering a high demand for skilled professionals. Salesforce is one of the most sought-after skills due to its crucial role in CRM and business management. Opting for Salesforce training in Hyderabad offers a significant edge, as the city’s robust job market is consistently growing. Leading companies like Google, Amazon, and Microsoft are actively searching for certified Salesforce experts to manage and optimize our Salesforce systems.
Specialists trained in Salesforce Admin, Developer (Apex), Lightning, and Integration modules are particularly valued. Certified professionals not only experience high demand but also enjoy competitive salaries in Hyderabad’s tech sector. This makes pursuing Salesforce training an excellent career decision, offering both financial rewards and opportunities for professional growth.
Why Choose CRS Info Solutions for Salesforce Training in Hyderabad?
Choosing the right Salesforce training in Hyderabad is crucial for a successful career. CRS Info Solutions is one of the top-rated Salesforce training institutes, offering a wide range of courses covering essential modules like Admin, Developer, Integration, and Lightning Web Components (LWC). With experienced instructors, CRS Info Solutions provides a comprehensive learning experience, combining both theoretical knowledge and practical application.
CRS Info Solutions is committed to helping you achieve Salesforce certification and build a promising career in the tech industry. The institute’s emphasis on practical learning and real-world applications ensures that you are fully prepared for opportunities in top companies like Google, Amazon, and Microsoft. With attractive salaries and a growing demand for Salesforce expertise in Hyderabad, investing in Salesforce training from CRS Info Solutions is the ideal way to secure a rewarding and successful career.