Famous Apex Interview Questions for Salesforce Developers [2025]

Whether you’re aiming for a new role or looking to strengthen your Apex skills, this comprehensive list of 30 Salesforce Apex interview questions and answers will help you prepare with confidence. From triggers and error handling to asynchronous processing and integration techniques, these questions cover a wide range of real-world scenarios that every Salesforce Developer should be ready to tackle.

1. What is a trigger?

A trigger in Salesforce is a piece of Apex code that executes automatically in response to certain events on a particular object. Triggers allow you to perform custom actions, such as updating related records, enforcing complex business logic, or automating processes when data changes in Salesforce.

trigger AccountTrigger on Account (before insert) {
    // Iterate through the new accounts being inserted
    for (Account newAcc : Trigger.new) {
        // Check if BillingCountryCode is null or empty
        if (newAcc.BillingCountryCode == null || String.isBlank(newAcc.BillingCountryCode)) {
            // Set a default country code
            newAcc.BillingCountryCode = 'US';
        }
    }
} 
// Just a basic example, not good practice to keep the Business logic in Trigger, we should use Handler classes 

2. What are various apex trigger context variables?

Trigger context variables” are special variables that are automatically available within a “trigger” in various programming and platform environments. Their purpose is to provide crucial information about why and how the trigger was activated, and what data is involved in that event.

  • Trigger.new Contains a list of new versions of the records that are being inserted or updated.
  • Trigger.old Contains a list of old versions of the records before they were updated or deleted.
  • Trigger.newMap A map of record IDs to their new versions (records being inserted or updated).
  • Trigger.oldMap A map of record IDs to their old versions (records before they were updated or deleted).
  • Trigger.isInsert Returns true if the trigger was fired due to an insert operation.
  • Trigger.isUpdate Returns true if the trigger was fired due to an update operation.
  • Trigger.isDelete Returns true if the trigger was fired due to a delete operation.
  • Trigger.isBefore Returns true if the trigger was fired before the record was saved to the database.
  • Trigger.isAfter Returns true if the trigger was fired after the record was saved to the database.

3. Difference between before and after triggers?

Before and After triggers in Salesforce are differentiated by when they execute in relation to the DML operation (e.g., INSERT, UPDATE, DELETE) and their purpose:

1. Timing:

Before Trigger: Executes before the record is saved to the database.
After Trigger: Executes after the record is saved to the database.

2. Purpose

Before Trigger: Primarily used to validate or modify data before it is committed to the database.
Example: Ensuring that a field is populated or updating a field value based on certain conditions.
Modifications made in Trigger.new are automatically saved; no explicit DML operation is required.
After Trigger: Used for actions that require access to the record’s database ID or related objects, which are only available after the record is saved.
Example: Creating related records, sending email notifications, or logging data to external systems.

4. Best Practices while Writing Triggers?

  • One Trigger Per Object:
    Write a single trigger per object to avoid conflicts and better manage logic.
  • Use Context Variables:
    Use context variables like Trigger.new, Trigger.old, Trigger.isInsert, Trigger.isUpdate, etc., to ensure appropriate behavior.
  • Avoid Hardcoding:
    Use custom settings, custom labels, or metadata to avoid hardcoding values.
  • Bulkify Your Trigger:
    Ensure the trigger handles bulk records by processing lists and collections instead of single records.
  • Avoid SOQL/DML in Loops:
    Move SOQL and DML operations outside loops to avoid hitting governor limits.
  • Use Helper Classes:
    Delegate complex logic to Apex helper classes for modularity and reusability.
  • Consider Trigger Order of Execution:
    Ensure triggers do not unintentionally conflict with workflows, processes, or other automations.
  • Error Handling:
    Implement trycatch blocks for exception handling, and provide meaningful error messages.

5. What is the size of Trigger.newMap in ‘before insert’?

The size of Trigger.newMap before insert is 0 since it’s not populated until records are inserted.

6. Best Practices in Apex

  • Write bulkified code to handle multiple records (e.g., use for loops carefully).
  • Avoid SOQL/DML inside loops to prevent governor limit issues.
  • Use collection types (e.g., maps, lists, sets) for efficient operations.
  • Implement proper exception handling.
  • Use @future and other asynchronous operations wisely for heavy processing.
  • Write test classes with 75%+ code coverage and meaningful assertions.

7. What Are Governor Limits?

Governor limits are Salesforce enforced limits that ensure efficient resource usage in a multitenant environment. Examples include:

  • SOQL Queries: Max 100 queries per transaction.
  • DML Statements issued: Max 150 per transaction.
  • Total records retrievd by soql 50000
  • Total records processed by dml 10000
  • Heap Size: 6 MB for synchronous and 12 MB for asynchronous Apex.( heap size refers to the amount of memory used by your Apex code during execution to store objects and variables at runtime.) Click here for more details

8. How do you call an external API from Apex?

Use HttpRequest and Http classes in Apex to call external APIs.
You must set up a Named Credential or Remote Site Setting to authorize the endpoint.
Handle responses using HttpResponse and parse the result (e.g., JSON) accordingly.

9. How do you resolve Error 151 in DML operations?

This error means too many DML statements (over 150) were executed in a transaction. To resolve it, bulkify your logic, use collections, and combine multiple updates. If needed, move processing to asynchronous Apex like Batch or Queueable.

10. What is the difference between Database.insert() and insert?

insert is a DML keyword that throws an exception and rolls back if even one record fails. Database.insert(list, false) allows partial success and returns a Database.SaveResult for each record. Use Database.insert when you want to handle failures gracefully.

11. How is error handling done in Salesforce Apex?

Error handling in Apex is done using try-catch-finally blocks. You can catch specific exceptions like DmlException, NullPointerException, etc. This allows the application to handle errors gracefully and continue execution where appropriate.

try {
    // Code that might throw an exception
    Account acc = new Account(Name = 'Test Account', Phone = '123-456-7890');
    insert acc; // This might fail if, for example, a validation rule prevents it

    // Another example: querying a record that might not exist
    // Account myAcc = [SELECT Id, Name FROM Account WHERE Name = 'Non Existent Account'];

} catch (DmlException e) {
    // Handle DML-specific exceptions (e.g., insert/update failures)
    System.debug('DML Exception caught: ' + e.getMessage());
    System.debug('DML Exception Type: ' + e.getExceptionType());
    System.debug('DML Exception Line Number: ' + e.getLineNumber());
    // Optionally, add a custom error message to the page or log to a custom object
    // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error inserting account: ' + e.getDmlMessage(0)));

} catch (QueryException e) {
    // Handle query-specific exceptions (e.g., no rows found for a single record query)
    System.debug('Query Exception caught: ' + e.getMessage());
    System.debug('Query Exception Type: ' + e.getExceptionType());
    // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error querying account: ' + e.getMessage()));

} catch (Exception e) {
    // Catch any other unexpected exceptions
    System.debug('General Exception caught: ' + e.getMessage());
    System.debug('General Exception Type: ' + e.getExceptionType());
    System.debug('General Exception Line Number: ' + e.getLineNumber());
    // This catch block should be the last one if you have multiple specific catch blocks
} finally {
    // Code in this block always executes, regardless of whether an exception occurred or not
    System.debug('Finally block executed.');
    // Often used for cleanup operations or closing resources (though less common in Apex than other languages)
}

12. What were Common Apex exceptions?

  • DmlException – Thrown when a DML operation (insert, update, delete) fails.
  • NullPointerException – Thrown when attempting to use a null object or variable.
  • QueryException – Thrown when a SOQL query fails (e.g., too many results or no results with getSingleResult).
  • LimitException – Thrown when governor limits (like SOQL, CPU time, heap) are exceeded.
  • StringException – Thrown for invalid string operations (e.g., outofbounds substring).
  • SObjectException – Thrown when performing invalid operations on SObjects (e.g., accessing an unpopulated field).

13. Use of helper class

A helper class moves business logic out of the trigger or controller, improving modularity. It makes your code cleaner, more reusable, and easier to test. It also helps implement the Trigger Handler design pattern.

14. Difference Between With and Without Sharing?

In Apex, with sharing and without sharing control whether your code respects the sharing rules of the user who’s running it. Think of sharing rules as who can see or change which records (like specific Accounts, Contacts, etc.).

with sharing: Your code respects the user’s sharing rules. If the user can’t normally see an account, your code won’t see it either. This is for when the code acts on behalf of the user.

without sharing: Your code ignores the user’s sharing rules. It can see and do things with all records, even if the user normally can’t. This is for when the code acts as a system administrator.

15. How to Delete Apex Class in Production?

To delete an Apex class from production, deploy a destructiveChanges.xml file using Workbench or ANT.
Ensure the class is not referenced and has 0% test coverage. Sandbox deletions won’t affect production unless deployed.

16. What is a Test Class?

A test class is used to write test methods that simulate user actions and validate Apex logic. It helps you achieve the required 75% code coverage for deployment. Test classes are isolated from real org data and are run in a separate context.

@IsTest
private class MyApexClass_Test { // Test class name usually ends with _Test

    @IsTest
    static void testMyMethod() {
        // 1. Prepare Test Data (Arrange)
        Account testAccount = new Account(Name = 'Test Account for Testing');
        insert testAccount;

        // 2. Call the Method/Trigger to be Tested (Act)
        // Assuming MyApexClass has a method named 'updateAccountDescription'
        // that updates an Account's Description field.
        MyApexClass.updateAccountDescription(testAccount.Id, 'This is a test description.');

        // 3. Verify Results (Assert)
        Account updatedAccount = [SELECT Id, Name, Description FROM Account WHERE Id = :testAccount.Id];
        System.assertEquals('This is a test description.', updatedAccount.Description, 'Account description was not updated correctly.');
    }

    @IsTest
    static void testAnotherScenario() {
        // Prepare different test data or edge cases
        Account anotherTestAccount = new Account(Name = 'Another Test Account', Phone = '123-456-7890');
        insert anotherTestAccount;

        // Perform another action
        MyApexClass.doSomethingElse(anotherTestAccount.Id);

        // Assert different outcomes
        // System.assert(some_condition, 'Optional failure message');
    }
}

17. What Are Annotations in Apex?

Annotations are metadata markers used in Apex to define the behavior of classes and methods. Common annotations:

  • @AuraEnabled: Exposes Apex methods to LWC and Aura.
  • @isTest: Marks a class or method as a test.
  • @future: Runs a method asynchronously.
  • @InvocableMethod: Enables methods to be called from flows.
  • @TestSetup: Creates test data reusable across multiple test methods.

18. What is error 101 in DML and how do you resolve it?

Error 101 means Too many SOQL queries in a single transaction (limit = 100). Refactor code to move SOQL outside loops and use Maps for caching. Consider asynchronous Apex if limits are still tight.

19. How do you handle DML errors?

Use try-catch blocks for synchronous DML.
Use Database.insert(records, false) for partial success and loop through Database.SaveResult[]. This allows better control and logging of individual record errors.

20. What is Batch Apex and when would you use it?

In Salesforce, Batch Apex is used to process large amounts of records efficiently by breaking them into smaller batches. Since normal Apex triggers and classes have limits (like processing only 50,000 records in one transaction), Batch Apex helps process millions of records without hitting those limits.

To Learn more about batch class please refer this https://trailhead.salesforce.com/content/learn/modules/asynchronous_apex/async_apex_batch

21. How do you schedule a Batch Apex job?

  • To schedule a Batch Apex job using Setup, go to Setup > Apex Classes and click on Schedule Apex.
  • Enter a meaningful job name, select your schedulable Apex class, and configure the frequency and start time.
  • Click Save, and Salesforce will automatically run your batch job as scheduled.

22. What was the Purpose of start, execute, and finish in Batch Apex?

  • start: Prepares and returns the data set (QueryLocator or Iterable).
  • execute: Processes batches of up to 200 records.
  • finish: Executes after all batches are done — great for chaining or sending notifications.

23. How do you chain Batch Apex jobs?

Chaining is done by calling Database.executeBatch() inside the finish() method. This ensures that the second batch starts only after the first completes. Used in multi-step processing or large job breakdowns.

24. What is Queueable Apex and when to use it?

Queueable Apex is an async process that runs later via the job queue. It allows you to chain jobs and pass complex types (like sObjects). Use it for background processing or when you exceed synchronous limits.

25. Difference between Queueable Apex and Future Methods?

  • Future methods only accept primitive types and don’t support chaining.
  • Queueable allows complex data and job monitoring via AsyncApexJob.
  • Queueable is more flexible and is the preferred pattern today.

26. Purpose of test class in Salesforce?

A test class ensures your code works as intended and doesn’t break future deployments. It simulates real use cases, performs assertions, and increases coverage. Required for deploying Apex code to production.

27. How to use Test.startTest() and Test.stopTest()?

These methods are used to separate test logic from Apex runtime limits. They reset governor limits and ensure asynchronous jobs (like future, queueable) run. Always wrap async calls between startTest() and stopTest().

28. What was the Purpose of System.assert() in test class?

System.assert() validates expected results in a test method. Use assertEquals() or assertNotEquals() to confirm logic correctness.
Assertions improve test reliability and identify incorrect logic early.

29. What was the difference between REST and SOAP APIs?

REST is lightweight, uses JSON, and supports CRUD via HTTP verbs (GET, POST).
SOAP uses XML, is more secure and formal, and better for enterprise systems.
Choose REST for mobile/web and SOAP for legacy integrations.

30. What were differnt ways to integrate Salesforce with external systems?

  • REST/SOAP APIs – Standard for web service calls.
  • Outbound Messaging – For notifying external systems on record change.
  • Platform Events, Apex Callouts, Mulesoft, and Named Credentials – For secure, scalable integrations.

Conclusion

Thanks for reading! I hope these questions helped clarify your understanding and gave you a boost in your interview prep. Please do follow for more salesforce stuff

Author

1 thought on “Famous Apex Interview Questions for Salesforce Developers [2025]”

Leave a Comment