SF Learners Hub

MASTER SALESFORCE, CONQUER YOUR GOALS

Top 20 Interview Questions & Answer -Part 2

Share This Post

Are you gearing up for a Salesforce Developer interview? Whether you’re a seasoned professional or just starting your journey, mastering the technical aspects of Salesforce development is crucial. To help you prepare effectively, we’ve compiled a list of 20 essential interview questions along with detailed answers. Let’s dive in!

1: Write an Aggregate Query to Count All Records where Case Status is New, Esclated, Open, or Closed.
SELECT Status, COUNT()
FROM Case
WHERE Status IN ('New', 'Escalated', 'Open', 'Closed')
GROUP BY Status
ORDER BY Status
2: Write an Aggregate Query to Count All Records where the Case Amount has the 2nd highest amount.
SELECT Amount__c, COUNT(Id)
FROM Case
GROUP BY Amount__c
ORDER BY Amount__c DESC
LIMIT 1
OFFSET 2
3: What is the difference between Custom Metadata & Custom Settings?

Custom Metadata Types: Custom metadata types are flexible data containers for your application that you can tailor to fit your needs. They’re easy to package, deploy, and update, making them ideal for configuring your app.

Custom Setting: Custom settings provide a way to store and retrieve data without needing to query the database using SOQL. However, unlike custom metadata types, you can’t directly create, update, or delete records using Apex with custom metadata types.

4: I have two users ‘XYZ’ & ‘ABC’. Write a Validation Rule to bypass this validation rule for the user ‘XYZ’.
AND(
  $User.Username <> 'XYZ',
  ISNEW()
)
5: Write a trigger to fetch all dates based on given days like if it is Monday then it should come 1,8,15,22.
trigger AccountTrigger on Account (before insert, before update) {
  // Define the days for which you want to fetch dates
  // Map to hold the day numbers and their corresponding dates
Map<Integer, List<Date>> dayToDateMap = new Map<Integer, List<Date>>();

// Get the current date
Date currentDate = Date.today();

// Get the day of the week for the current date
Integer dayOfWeek = currentDate.day();

// Iterate to fetch the next 4 dates based on the day of the week
for (Integer i = 0; i < 4; i++) {
  if (!dayToDateMap.containsKey(dayOfWeek)) {
      dayToDateMap.put(dayOfWeek, new List<Date>());
  }
  dayToDateMap.get(dayOfWeek).add(currentDate);
  currentDate = currentDate.addDays(7); // Add 7 days to get the next date of the same day
}

}
6: What are the different types of Asynchronous Apex?

Asynchronous Apex offers developers various tools for executing code outside the immediate transaction context, catering to different scenarios and processing needs within Salesforce applications. The primary types of Asynchronous Apex include Future Methods, Queueable Apex, Batch Apex, and Scheduled Apex.

  • Future Methods enable the asynchronous execution of lightweight tasks by running methods in a separate thread, aiding in offloading non-urgent operations like callouts. They’re invoked by annotating a method with the @future annotation, allowing for parallel execution without impacting the main transaction’s performance. However, they have limitations, such as the inability to return values synchronously.
  • Queueable Apex provides greater control over asynchronous processing, allowing developers to execute complex, long-running tasks in the background. By implementing the Queueable interface, jobs can be enqueued for execution using System.enqueueJob(), making it suitable for handling more intricate data transformations or batch processing tasks. Queueable Apex can chain up to 50 jobs, offering scalability and efficient resource utilization.
  • Batch Apex facilitates the processing of large data sets by dividing them into manageable chunks, each processed in its transaction. With the Database.Batchable interface, developers can define how records are processed in batches, making it ideal for data cleansing, migration, or complex calculations. Batch Apex can process millions of records efficiently, providing methods for handling start, execute, and finish processing, along with DML operations.
  • Scheduled Apex automates the execution of Apex classes at specified intervals, allowing for regular, recurring tasks to be performed without manual intervention. By implementing the Schedulable interface, developers can define the schedule for job execution, enabling activities like data backups or periodic maintenance. While Scheduled Apex provides flexibility in scheduling tasks, it’s subject to limits based on the number of scheduled jobs per organization.
7: What are the different sharing models we use to share records in Salesforce?

Here are the primary sharing models in Salesforce:

  • Organization-Wide Defaults (OWD): OWD settings establish the baseline level of access to records for all users in an organization. OWD settings have a significant impact on overall data security and privacy within the organization, as they dictate the default level of access to records.
    • Private: Only the record owner has full access. Other users can only access records they own or have been granted access to via sharing rules or manual sharing.
    • Public Read-Only: All users can view records, but only the owner and users higher up in the role hierarchy can edit them.
    • Public Read/Write: All users can view and edit all records.
    • Controlled by Parent: Access to child records is determined by the parent’s sharing setting.
  • Role Hierarchy: Represents the reporting structure within the organization. Users higher in the role hierarchy automatically have access to records owned by users reporting to them. The role hierarchy facilitates data visibility according to managerial relationships, ensuring appropriate access to records based on reporting structure.
  • Sharing Rules: Extend access beyond the role hierarchy based on specified criteria. Admins define criteria to identify records and specify which users or groups should have access to them. Grants read-only or read/write access to selected users or groups based on the defined criteria.
  • Manual Sharing: Allows users or administrators to manually share individual records with other users or groups. Provides read-only or read/write access to specific users or groups on a case-by-case basis. Manual sharing enables ad-hoc sharing of individual records, providing flexibility for granting access outside the scope of role hierarchy or sharing rules.
  • Apex-Based Sharing: Enables programmatic control over sharing through custom Apex code. Developers can use Apex to define complex sharing rules based on business logic, extending beyond standard sharing mechanisms. Allows for fine-grained control over record access, with the ability to enforce custom sharing logic. Apex-based sharing is useful for scenarios that require highly customized sharing rules or interactions with external systems.
8: What are the different types of relationships in Salesforce?

There are several types of relationships in Salesforce, each serving specific purposes:

  1. Lookup Relationship:
    • A lookup relationship is a basic association between two objects where one object (the child) has a reference (lookup field) to another object (the parent).
    • It’s a one-to-one or one-to-many relationship where the child record can have a reference to only one parent record.
    • Lookup relationships are commonly used when there is no strict enforcement of referential integrity required between the objects.
  2. Master-Detail Relationship:
    • A master-detail relationship is a type of parent-child relationship where the detail (child) record is tightly related to its master (parent) record.
    • It’s a one-to-many relationship where the detail record cannot exist without a master record and is automatically deleted when its master record is deleted.
    • Master-detail relationships offer more control and functionality compared to lookup relationships, such as roll-up summary fields and cascading deletes.
  3. Many-to-Many Relationship:
    • Many-to-many relationships allow records in one object to be linked to multiple records in another object and vice versa.
    • Implemented using junction objects, which serve as intermediary objects that connect two objects with many-to-many relationships through two separate master-detail relationships.
    • Many-to-many relationships are useful for modeling complex data structures where multiple records need to be related to each other.
  4. Hierarchy Relationship:
    • Hierarchy relationships are specific to certain standard objects in Salesforce, such as User, Account, and Opportunity.
    • These relationships define hierarchical structures, such as the manager-subordinate relationship in the User object or the account hierarchy in the Account object.
    • Hierarchy relationships enable functionalities like reporting up the management chain or rolling up data across hierarchical levels.
  5. External Lookup Relationship:
    • External lookup relationships establish connections between Salesforce objects and records in external systems.
    • They allow Salesforce to reference records in external data sources using external IDs or other unique identifiers.
    • External lookup relationships are essential for integrating Salesforce with external systems and leveraging data from external sources within Salesforce.
9: What is the difference between With Sharing & Without Sharing?
with sharingwithout sharing
Enforces sharing rules and permissions.Does not enforce sharing rules and permissions.
Respects organization-wide defaults (OWD) and sharing rules.Ignores OWD and sharing rules; provides access to all records.
User access is restricted based on their permissions and sharing settings.User access is not restricted; all records are accessible.
Adheres to the principle of least privilege, enhancing security.May potentially expose sensitive data, requires careful handling.
10: What is the order we are following in Record Sharing?
11: What is DOM & Shadow DOM in LWC?

In Lightning Web Components (LWC), the DOM (Document Object Model) and Shadow DOM play crucial roles in defining the structure and behavior of components. Here’s a brief explanation of each:

DOM (Document Object Model):

  • The Document Object Model (DOM) is a programming interface that represents the structure of a web page as a tree of objects.
  • In LWC, the DOM represents the hierarchical structure of HTML elements that make up a component’s template. Each element in the DOM is represented as a node, and you can interact with these nodes using JavaScript to manipulate the content and behavior of the component.
  • The DOM in LWC is used to render the UI (User Interface) of components based on the component’s template markup.

Shadow DOM (Shadow Document Object Model):

  • The Shadow DOM is a subset of the DOM that encapsulates the styling and behavior of a component, shielding it from the global styles and scripts of the parent document.
  • In LWC, each component gets its own Shadow DOM by default. This means that the HTML markup and CSS styles defined within a component are scoped to that component and do not affect the parent document or other components on the page.
  • The Shadow DOM helps in building encapsulated and reusable components by providing a way to isolate the component’s structure, styles, and behavior from the rest of the page.
12: How to call Apex Class Imperatively?

To call an Apex class imperatively in a Lightning Web Component (LWC), import the Apex method and invoke it using JavaScript. Here’s a concise example:

import myApexMethod from '@salesforce/apex/MyApexClass.myApexMethod';

myApexMethod({ inputParameter: 'example' })
    .then(result => {
        console.log('Apex result:', result);
    })
    .catch(error => {
        console.error('Error calling Apex:', error);
    });
13: What are the different ways we are using to share records using Sharing Rules?

In Salesforce, you can use Sharing Rules to share records with other users or groups. There are three main types of sharing rules:

  1. Criteria-Based Sharing Rules:
    Criteria-based sharing Rules allow you to share records based on certain criteria. For example, you can share records where the Region equals ‘North America’ with a specific group of users. These rules are created based on criteria defined in a sharing rule definition. They are evaluated when a record is created or updated and automatically grant access to records that meet the specified criteria.
  2. Owner-Based Sharing Rules:
    Owner-Based Sharing Rules automatically grant access to records owned by certain users or groups to other users or groups. For instance, you can automatically share records owned by a particular user with a specific group of users or roles. These rules are based on the owner of the record and are evaluated whenever ownership changes.
  3. Manual Sharing:
    Manual Sharing allows users with the appropriate permissions to manually share individual records with other users or groups. This can be done on a record-by-record basis, giving users more granular control over sharing. Users can grant read or read/write access to other users or groups, and these manual shares can be revoked if necessary.
14: How to Call one Batchable Class from another batchable Class?

To call one Batchable class from another in Salesforce, you can use the Database.executeBatch() method. Here’s how you can do it:

FirstBatchable.apxc Class

public class FirstBatchable implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        // Your start method logic here
    }

    public void execute(Database.BatchableContext bc, List<sObject> scope) {
        // Your execute method logic here
    }

    public void finish(Database.BatchableContext bc) {
        // Your finish method logic here
    }
}

SecondBatchable.apxc Class

public class SecondBatchable implements Database.Batchable<sObject> {
    public void execute(Database.BatchableContext bc, List<sObject> scope) {
        // Your execute method logic here

        // Call the FirstBatchable class
        FirstBatchable batchable = new FirstBatchable();
        Database.executeBatch(batchable);
    }
}
15: Business Requirement: I want to update all the contact address fields associated with the Account Record after the account update record.
trigger UpdateContactAddressOnAccountUpdate on Account (after update) {
    // List to hold the contact records to update
    List<Contact> contactsToUpdate = new List<Contact>();

    // Iterate through the trigger context records
    for (Account acc : Trigger.new) {
        // Retrieve the old account record for comparison
        Account oldAcc = Trigger.oldMap.get(acc.Id);

        // Check if the address fields have been updated
        if (acc.BillingStreet != oldAcc.BillingStreet ||
            acc.BillingCity != oldAcc.BillingCity ||
            acc.BillingState != oldAcc.BillingState ||
            acc.BillingPostalCode != oldAcc.BillingPostalCode ||
            acc.BillingCountry != oldAcc.BillingCountry) {
            
            // Query for the related Contact records
            List<Contact> relatedContacts = [SELECT Id, MailingStreet, MailingCity, MailingState, MailingPostalCode, MailingCountry
                                             FROM Contact WHERE AccountId = :acc.Id];

            // Update the related Contact records with the new address fields
            for (Contact con : relatedContacts) {
                con.MailingStreet = acc.BillingStreet;
                con.MailingCity = acc.BillingCity;
                con.MailingState = acc.BillingState;
                con.MailingPostalCode = acc.BillingPostalCode;
                con.MailingCountry = acc.BillingCountry;

                // Add the modified Contact record to the list
                contactsToUpdate.add(con);
            }
        }
    }

    // Update the Contact records
    if (!contactsToUpdate.isEmpty()) {
        update contactsToUpdate;
    }
}
16: Business Requirement: I want to call the approval process on the given multiple conditions. if the Reimbursement Amount is less than 1000 then it goes for approval to the Accounts Team, and if the Reimbursement Amount is greater than 1000 and less than 5000 then it goes for the first approval to the Manager and then 2nd approval goes for the Accounts team, and if the Reimbursement Amount is greater than 5000 then it goes for the first approval to the Manager and then 2nd approval goes for the DU Head and final approval goes to the Accounts team.
  • Define three approval processes in Salesforce: one for each scenario described in the requirements (less than 1000, between 1000 and 5000, greater than 5000).
  • Configure the approval steps and approvers as per the given conditions.
17: Define the Different Methods of Batchable Class & Schedulable Class.

Batchable Class:

  1. start (Database.BatchableContext):
    • This method returns a Database.QueryLocator object or an iterable that identifies the records to be processed.
    • It’s invoked at the beginning of the batch job to start the processing.
  2. execute (Database.BatchableContext, List<sObject>):
    • This method processes the records returned by the start method.
    • It’s called multiple times with different batches of records until all records are processed.
  3. finish (Database.BatchableContext):
    • This method is called once after all records are processed by the execute method.
    • It’s typically used to perform any post-processing tasks or cleanup operations.

Schedulable Class:

  1. execute (SchedulableContext):
    • This method contains the main logic to be executed when the scheduled job runs.
    • It’s invoked when the scheduled job is executed based on the specified schedule.
18: What are the different Ways to make the required field and read-only fields?

In Salesforce, you have several options to make fields required or read-only. Here are some ways to achieve this:

  • To make a field read-only, you can adjust the field-level security settings for the respective profiles or permission sets.
  • Required fields are denoted by a red asterisk (*) on the page layout.
  • We can configure fields as required or read-only directly on the page layout.
  • We can create validation rules to make the fields required.
  • We can configure field dependencies to make fields required or read-only based on the value of controlling fields.
  • We can configure fields as required or read-only directly on Dynamic Forms.
19: What are the lifecycle hooks in LWC?

Here are the lifecycle hooks available in LWC:

  • constructor
  • connectedCallback
  • renderedCallback
  • renderCallback
  • disconnectedCallback
  • errorCallback
19: How can we track Success Records in Batch class?

In Salesforce, if you want to keep track of success records in a batch class, you can utilize the Database.Stateful interface in your class declaration. This interface enables the class to maintain its state across multiple batches, allowing you to track progress and keep records of both processed and failed records.

20: Business Requirement: I have two project records P1 & P2, and I have assigned P1 Record to the PM1 and TL1 and I have assigned the P2 Record to the PM2 and TL2. then, How can you send the email to the Particular PM & TL for the respective assigned project?

ProjectUpdateTrigger

trigger ProjectUpdateTrigger on Project__c (after update) {
    public static void sendProjectEmails(List<Project__c> updatedProjects) {
        ProjectEmailSender.sendProjectEmails(updatedProjects);
    }

    // Call sendProjectEmails method
    sendProjectEmails(Trigger.new);
}

ProjectEmailSender.apxc

public class ProjectEmailSender {
    public static void sendProjectEmails(List<Project__c> updatedProjects) {
        // Iterate through each updated project
        for(Project__c project : updatedProjects) {
            // Check if Project Manager or Team Lead has changed
            if(Trigger.oldMap.get(project.Id).Project_Manager__c != project.Project_Manager__c) {
                sendEmail(project.Project_Manager__c, 'Project Manager', project.Name);
            }
            if(Trigger.oldMap.get(project.Id).Team_Lead__c != project.Team_Lead__c) {
                sendEmail(project.Team_Lead__c, 'Team Lead', project.Name);
            }
        }
    }

    public static void sendEmail(String recipient, String role, String projectName) {
        // Construct email message
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new List<String>{recipient});
        email.setSubject('Project Assignment Update');
        email.setPlainTextBody('Dear ' + role + ',\n\nYour assignment has been updated for project: ' + projectName);

        // Send email
        Messaging.SendEmailResult[] results = Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
        
        // Check results and handle any errors
        for(Messaging.SendEmailResult result : results) {
            if(result.isSuccess()) {
                System.debug('Email sent successfully');
            } else {
                System.debug('Error sending email: ' + result.getErrors()[0].getMessage());
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Extract Valuable Data with Salesforce OCR

Revolutionize the way you handle and utilize your documents with OCR in Salesforce. Optical Character Recognition will enhance your data management and streamline business processes.