Skip to content
  1. Home
  2. Interview Questions
  3. Salesforce Apex
Enterprise & Legacy

100 Salesforce Apex Interview Questions and Answers (2026)

The most asked Salesforce Apex interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.

Updated November 2026 Reviewed by Abhishek Kumar 120 min read
100Questions
15Freshers
15Intermediate
60Experienced

Key takeaways

  • 100 Salesforce Apex interview questions, grouped by level: freshers, intermediate, experienced and coding.
  • Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
  • Use the filter bar to practise only the level you are interviewing for, then test yourself with the free Salesforce Apex quiz.

What is Salesforce Apex, and why do interviewers ask about it?

This page contains a carefully selected collection of Apex Interview Questions and Answers designed for students, Salesforce beginners, software developers, and experienced professionals preparing for Salesforce developer interviews. The questions cover both theoretical concepts and practical programming examples commonly asked during technical interviews.

Apex is Salesforce's strongly typed, object-oriented programming language used to build business logic on the Salesforce Platform. It enables developers to create triggers, classes, asynchronous jobs, REST services, integrations, and custom automation while working securely with Salesforce data.

This interview guide covers beginner, intermediate, advanced, and scenario-based Apex interview questions including Apex syntax, triggers, SOQL, SOSL, governor limits, collections, asynchronous Apex, exception handling, testing, batch processing, integrations, and best practices followed by Salesforce developers.

Why companies hire for Salesforce Apex

  • Purpose-built for the Salesforce platform – tightly integrated with CRM data and metadata
  • Strongly typed and object-oriented – ensures reliability and maintainability
  • Built-in governor limits – enforces efficient, scalable code in multi-tenant environments
  • Full support for CRUD, SOQL, SOSL, and DML operations – seamless data manipulation
  • Asynchronous capabilities – batch jobs, queueable, and scheduled Apex for background processing
  • Robust testing framework – built-in support for test classes and code coverage
  • Highly demanded skill – essential for Salesforce developers and architects worldwide

Basic Salesforce Apex Interview Questions for Freshers

15 questions

Start here if you are a fresher or switching to Salesforce Apex. These fundamentals are asked in almost every first-round and campus interview.

How interviewers ask it“Let's start with the basics — how would you explain Apex?”

What is Apex?

BeginnerSalesforce Apex
Quick answerApex is a strongly typed, object-oriented programming language developed by Salesforce for building enterprise applications on the Salesforce Platform. It runs entirely on the Salesforce cloud and is used to implement business logic, automate processes, and integrate with external systems.
  • Object-oriented – supports classes, interfaces, inheritance
  • Strongly typed – compile-time type checking
  • Database integration – native SOQL and DML operations
  • Multitenant aware – designed for Salesforce's shared environment
  • Asynchronous support – future methods, batch, queueable
Java
public class MyHelloWorldClass {
    public static void sayHello() {
        System.debug('Hello World from Apex!');
    }
}

How interviewers ask it“Let's start with the basics — how would you explain the key features of Apex?”

What are the key features of Apex?

BeginnerSalesforce Apex
Quick answerApex is object-oriented, strongly typed, multitenant aware, integrated directly with the database, and provides built-in support for transactional triggers as well as complex asynchronous processing loops.
Java
Account acc = new Account(Name = 'Acme Corp');
insert acc;

How interviewers ask it“Let's start with the basics — how would you explain a governor limit in Apex?”

What is a Governor Limit?

BeginnerSalesforce Apex
Quick answerGovernor limits are runtime limits enforced by the Salesforce multitenant engine to prevent shared execution threads from monopolizing system resources.
Java
// Bulkified query and list insert
List<Contact> contactsToInsert = new List<Contact>();

for (Account acc : [SELECT Id FROM Account LIMIT 100]) {
    contactsToInsert.add(
        new Contact(
            LastName = 'Doe',
            AccountId = acc.Id
        )
    );
}

insert contactsToInsert;

How interviewers ask it“In simple words, what is SOQL? Explain it like you would to a new teammate.”

What is SOQL?

BeginnerSalesforce Apex
Quick answerSOQL (Salesforce Object Query Language) is used to read data structures and records from individual object structures.
Java
List<Opportunity> opps = [
    SELECT Id, Name, Amount, StageName
    FROM Opportunity
    WHERE CloseDate = TODAY
];

How interviewers ask it“In simple words, what is SOSL? Explain it like you would to a new teammate.”

What is SOSL?

BeginnerSalesforce Apex
Quick answerSOSL (Salesforce Object Search Language) is used to scan text patterns across multiple index tables at once.
Java
List<List<SObject>> searchList = [
    FIND 'Acme*'
    IN ALL FIELDS
    RETURNING
        Account(Name),
        Contact(FirstName, LastName)
];

How interviewers ask it“Can you compare SOQL and SOSL? Where do people usually confuse them?”

Difference between SOQL and SOSL?

BeginnerSalesforce Apex
Quick answerSOQL retrieves exact records from a single object index, whereas SOSL performs multi-object keyword searches efficiently across text columns.
Java
// SOQL (Exact retrieval)
Account acc = [
    SELECT Id
    FROM Account
    WHERE Name = 'Acme'
    LIMIT 1
];

// SOSL (Fuzzy search)
List<List<SObject>> results = [
    FIND 'Acme'
    IN NAME FIELDS
    RETURNING Account(Id, Name)
];

How interviewers ask it“Let's start with the basics — how would you explain a trigger in Apex?”

What is a Trigger in Apex?

BeginnerSalesforce Apex
Quick answerA trigger is Apex code that runs dynamically before or after specific DML operations, such as record insertions, edits, or removals.
Java
trigger AccountTrigger on Account (before insert, before update) {

    for (Account acc : Trigger.new) {

        if (acc.Industry == null) {
            acc.Industry.addError('Industry is required.');
        }

    }

}

How interviewers ask it“In simple words, what are DML statements? Explain it like you would to a new teammate.”

What are DML statements?

BeginnerSalesforce Apex
Quick answerData Manipulation Language statements modify records in the Salesforce database (e.g., insert, update, delete, undelete, upsert ).

Data Manipulation Language statements modify records in the Salesforce database (e.g., insert, update, delete, undelete, upsert).

Java
List<Account> newAccs = new List<Account>{
    new Account(Name = 'Tech Corp'),
    new Account(Name = 'Media Group')
};

insert newAccs;

How interviewers ask it“Let's start with the basics — how would you explain a class in Apex?”

What is a Class in Apex?

BeginnerSalesforce Apex
Quick answerA class is a structural template or object-oriented blueprint containing processing methods and properties.
Java
public class Vehicle {

    private String model;

    public Vehicle(String modelName) {
        this.model = modelName;
    }

}

How interviewers ask it“In simple words, what are access modifiers? Explain it like you would to a new teammate.”

What are Access Modifiers in Apex?

BeginnerSalesforce Apex
Quick answerApex provides four levels of visibility control: public, private, protected, and global.
Java
global class GlobalService {

    public static void performTask() {

        // Shared across namespaces and API integrations

    }

}

How interviewers ask it“In simple words, what is a static variable? Explain it like you would to a new teammate.”

What is a Static variable?

BeginnerSalesforce Apex
Quick answerA static variable is scoped to the class itself rather than individual instances, and persists across execution contexts.
Java
public class Counter {

    public static Integer staticCount = 0; // Class-level shared state

    public Integer instanceCount = 0; // Object-level individual state

}

How interviewers ask it“In simple words, what is a constructor? Explain it like you would to a new teammate.”

What is a Constructor?

BeginnerSalesforce Apex
Quick answerA constructor is a special class method called automatically during object instantiation to initialize state.
Java
public class Employee {

    public String name;

    public Employee(String empName) {
        this.name = empName;
    }

}

How interviewers ask it“Let's start with the basics — how would you explain batch Apex?”

What is Batch Apex?

BeginnerSalesforce Apex
Quick answerBatch Apex processes massive datasets asynchronously by splitting operations into smaller, manageable transaction blocks called chunks.
Java
public class AccountUpdateBatch implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext bc) {

        return Database.getQueryLocator(
            'SELECT Id FROM Account'
        );

    }

    public void execute(
        Database.BatchableContext bc,
        List<Account> scope
    ) {

        // Process each chunk safely

    }

    public void finish(Database.BatchableContext bc) {

        // Post-processing logic

    }

}

How interviewers ask it“In simple words, what is a future method? Explain it like you would to a new teammate.”

What is a Future Method?

BeginnerSalesforce Apex
Quick answerA future method (annotated with @future) executes asynchronously in its own thread block when resources become available.
Java
public class AsyncHelper {

    @future
    public static void callExternalWebService(String payload) {

        // Async processing

    }

}

How interviewers ask it“In simple words, what is a test class? Explain it like you would to a new teammate.”

What is a Test Class?

BeginnerSalesforce Apex
Quick answerA test class contains verification logic to test Apex code functionality, and is required to hit a minimum 75% code coverage threshold for production deployments.
Java
@isTest
private class AccountServiceTest {

    @isTest
    static void testAccountCreation() {

        Account acc = new Account(Name = 'Test Acc');

        insert acc;

        System.assertNotEquals(
            null,
            acc.Id,
            'Account ID should be generated'
        );

    }

}

Intermediate Salesforce Apex Interview Questions

15 questions

Questions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with Salesforce Apex.

How interviewers ask it“Explain bulkification in Apex in detail — what should a new team member understand about it?”

What is Bulkification?

IntermediateSalesforce Apex
Quick answerBulkification is the practice of designing code to handle sets of records efficiently in a single operation, rather than processing individual records one-by-one inside loop blocks.
Java
// BAD (Trigger with nested query)

// for (Account a : Trigger.new) {
//     List<Contact> c = [
//         SELECT Id
//         FROM Contact
//         WHERE AccountId = :a.Id
//     ];
// }

// GOOD (Bulkified query mapping)

Set<Id> accIds = new Set<Id>();

for (Account a : Trigger.new) {
    accIds.add(a.Id);
}

List<Contact> contacts = [
    SELECT Id, LastName
    FROM Contact
    WHERE AccountId IN :accIds
];

How interviewers ask it“Walk me through a wrapper class in Apex. Where does it come up in real systems?”

What is a Wrapper Class?

IntermediateSalesforce Apex
Quick answerA wrapper class is a custom container object used to bind multiple distinct data types or sObjects together into a single logical structure.
Java
public class TableWrapper {

    public Account accRecord { get; set; }

    public Boolean isSelected { get; set; }

    public TableWrapper(Account a) {

        this.accRecord = a;
        this.isSelected = false;

    }

}

How interviewers ask it“How would you explain a map to a junior engineer, and what do people most often get wrong?”

What is a Map in Apex?

IntermediateSalesforce Apex
Quick answerA map is an un-ordered collection that stores data in key-value pairs, where each key uniquely maps to a single corresponding value.
Java
Map<Id, Account> accountMap =
    new Map<Id, Account>([
        SELECT Id, Name
        FROM Account
        LIMIT 10
    ]);

Account target =
    accountMap.get('0018000000GvNX0AAN');

How interviewers ask it“Explain a set in Apex in detail — what should a new team member understand about it?”

What is a Set in Apex?

IntermediateSalesforce Apex
Quick answerA set is an unordered collection of elements that enforces uniqueness, preventing duplicate entries from being added to the collection.
Java
Set<String> uniqueCodes =
    new Set<String>{
        'US',
        'UK',
        'CA',
        'US'
    };

System.debug(uniqueCodes.size()); // Outputs 3

How interviewers ask it“How would you explain a list to a junior engineer, and what do people most often get wrong?”

What is a List in Apex?

IntermediateSalesforce Apex
Quick answerA list is an ordered collection of elements indexed by position. It can contain duplicate values and functions like a standard dynamic array.
Java
List<String> names = new List<String>();

names.add('Akash');
names.add('Rahul');

String first = names.get(0);

How interviewers ask it“Explain queueable Apex in detail — what should a new team member understand about it?”

What is Queueable Apex?

IntermediateSalesforce Apex
Quick answerQueueable Apex is an asynchronous design pattern that builds upon future methods, allowing you to monitor job status and chain sequential asynchronous execution flows.
Java
public class AsyncProcessor implements Queueable {

    public void execute(QueueableContext context) {

        // Chainable async operation
        System.enqueueJob(new SecondaryProcessor());

    }

}

How interviewers ask it“How would you explain SObject to a junior engineer, and what do people most often get wrong?”

What is SObject?

IntermediateSalesforce Apex
Quick answerAn sObject is a generic data type that can represent any standard or custom Salesforce object record in memory.
Java
sObject genericRecord =
    new Account(Name = 'Generic Corp');

String objName =
    genericRecord
        .getSObjectType()
        .getDescribe()
        .getName();

How interviewers ask it“How would you explain schema builder to a junior engineer, and what do people most often get wrong?”

What is Schema Builder?

IntermediateSalesforce Apex
Quick answerSchema Builder is a visual design utility inside Salesforce used to manage data models, define objects, and establish relationship connections. At the code level, you describe these schemas programmatically.
Java
Map<String, Schema.SObjectType> gd =
    Schema.getGlobalDescribe();

Schema.DescribeSObjectResult descResult =
    gd.get('Account').getDescribe();

How interviewers ask it“How would you explain with sharing to a junior engineer, and what do people most often get wrong?”

What is With Sharing?

IntermediateSalesforce Apex
Quick answerThe with sharing keyword enforces the organization-wide defaults and sharing rules of the running user for all database queries and transactions in that class.
Java
public with sharing class SecureRecordController {

    // Respects sharing rules
    // of current logged-in user

}

How interviewers ask it“Walk me through without sharing in Apex. Where does it come up in real systems?”

What is Without Sharing?

IntermediateSalesforce Apex
Quick answerThe without sharing keyword executes class logic in system mode, ignoring the current user's sharing rules and record permissions.
Java
public without sharing class AdminDataOverrider {

    // Skips sharing rules
    // and operates with system-level access

}

How interviewers ask it“Walk me through upsert in Apex. Where does it come up in real systems?”

What is Upsert?

IntermediateSalesforce Apex
Quick answerThe upsert command checks if a record exists based on an ID or unique external ID field; it updates the record if found, or inserts a new record if it is not.
Java
Account acc = new Account(
    Name = 'Upsert Corp',
    External_ID__c = 'EXT-101'
);

upsert acc External_ID__c;

How interviewers ask it“Explain database class in Apex in detail — what should a new team member understand about it?”

What is Database Class?

IntermediateSalesforce Apex
Quick answerThe Database class provides system methods for database manipulation, supporting partial successes via the allOrNone parameter option.
Java
Database.SaveResult[] srList =
    Database.insert(accountList, false);

// false allows partial success

How interviewers ask it“How would you explain trigger context variable to a junior engineer, and what do people most often get wrong?”

What is Trigger Context Variable?

IntermediateSalesforce Apex
Quick answerTrigger context variables (e.g., Trigger.new, Trigger.oldMap, Trigger.isInsert) provide operational state and data from the triggering transaction.
Java
trigger ContactTrigger on Contact (before update) {

    for (Contact newCon : Trigger.new) {

        Contact oldCon =
            Trigger.oldMap.get(newCon.Id);

        if (newCon.Email != oldCon.Email) {

            System.debug(
                'Email changed from '
                + oldCon.Email
            );

        }

    }

}

How interviewers ask it“How would you explain callout to a junior engineer, and what do people most often get wrong?”

What is Callout in Apex?

IntermediateSalesforce Apex
Quick answerA callout executes HTTP requests from Apex to integrate and exchange payload data with external web services.
Java
Http http = new Http();

HttpRequest request = new HttpRequest();

request.setEndpoint(
    'https://api.example.com/data'
);

request.setMethod('GET');

HttpResponse response =
    http.send(request);

How interviewers ask it“Walk me through exception handling in Apex. Where does it come up in real systems?”

What is Exception Handling?

IntermediateSalesforce Apex
Quick answerException handling uses try-catch-finally blocks to intercept runtime errors, handle failures gracefully, and execute mandatory cleanup actions.
Java
try {

    insert new Lead(LastName = 'Smith');

}
catch (DmlException e) {

    System.debug(
        'DML failed: ' + e.getMessage()
    );

}
finally {

    System.debug(
        'Transaction finished processing.'
    );

}

Advanced Salesforce Apex Interview Questions for Experienced Developers

60 questions

Senior-level Salesforce Apex questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.

How interviewers ask it“How would you explain Lightning web component integration to a junior engineer, and what do people most often get wrong?”

What is Lightning Web Component integration with Apex?

AdvancedSalesforce Apex
Quick answerApex methods annotated with @AuraEnabled allow client-side Lightning Web Components (LWC) to call server-side actions, retrieve database records, or trigger business logic.
Java
public class ContactController {

    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactList() {

        return [
            SELECT Id, FirstName, LastName
            FROM Contact
            LIMIT 10
        ];

    }

}

How interviewers ask it“Explain platform event in Apex in detail — what should a new team member understand about it?”

What is Platform Event?

AdvancedSalesforce Apex
Quick answerPlatform Events support an event-driven architecture, enabling applications to run independently by publishing and subscribing to real-time notification streams.
Java
Order_Event__e eventObj =
    new Order_Event__e(
        Order_Id__c = 'ORD-009',
        Status__c = 'Shipped'
    );

Database.SaveResult sr =
    EventBus.publish(eventObj);

How interviewers ask it“How would you explain mixed DML error to a junior engineer, and what do people most often get wrong?”

What is Mixed DML Error?

AdvancedSalesforce Apex
Quick answerA Mixed DML error occurs when you try to modify a setup object (like User) and a non-setup object (like Account) in the same transaction context.
Java
User u = [
    SELECT Id
    FROM User
    WHERE Alias = 'admin'
];

System.runAs(u) {

    // Update User (Setup Object)

}

// Update Account (Non-Setup Object)
// outside block

How interviewers ask it“Walk me through Apex scheduler. Where does it come up in real systems?”

What is Apex Scheduler?

AdvancedSalesforce Apex
Quick answerThe Apex Scheduler executes specific classes at scheduled intervals by implementing the Schedulable interface.
Java
public class CleanupScheduler
    implements Schedulable {

    public void execute(SchedulableContext sc) {

        // Delete orphaned logs dynamically

    }

}

How interviewers ask it“Explain custom metadata type in Apex in detail — what should a new team member understand about it?”

What is Custom Metadata Type?

AdvancedSalesforce Apex
Quick answerCustom Metadata Types are application configurations that can be packaged and deployed between environments. They are read from cache without consuming SOQL query limits.
Java
App_Setting__mdt setting =
    App_Setting__mdt.getInstance(
        'Global_Config'
    );

Boolean featureEnabled =
    setting.Is_Active__c;

How interviewers ask it“Explain Field-Level security in Apex in detail — what should a new team member understand about it?”

What is Field-Level Security?

AdvancedSalesforce Apex
Quick answerField-Level Security (FLS) manages user access to specific fields on objects. It should be validated dynamically in Apex before querying or mutating field data.
Java
if (
    Schema.sObjectType.Contact
        .fields.Email.isAccessible()
) {

    // Query/Read field safely

}

How interviewers ask it“How would you explain dynamic SOQL to a junior engineer, and what do people most often get wrong?”

What is Dynamic SOQL?

AdvancedSalesforce Apex
Quick answerDynamic SOQL allows you to construct and execute SOQL query strings at runtime using the Database.query() method.
Java
String dynamicField = 'Phone, Email';

String queryStr =
    'SELECT Id, '
    + dynamicField
    + ' FROM Lead LIMIT 5';

List<Lead> leads =
    Database.query(queryStr);

How interviewers ask it“How would you explain savepoint to a junior engineer, and what do people most often get wrong?”

What is Savepoint?

AdvancedSalesforce Apex
Quick answerA Savepoint defines a specific state in a transaction that you can roll back to in case of errors, without reverting the entire transaction.
Java
Savepoint sp =
    Database.setSavepoint();

try {

    insert new Account(
        Name = 'Success'
    );

    insert new Contact();

    // Fails due to missing LastName

}
catch (Exception e) {

    Database.rollback(sp);

    // Reverts transaction

}

How interviewers ask it“Explain a custom setting in Apex in detail — what should a new team member understand about it?”

What is a Custom Setting?

AdvancedSalesforce Apex
Quick answerCustom Settings are application configurations cached in memory. They provide fast read access without using SOQL query limits.
Java
Discount_Setting__c discount =
    Discount_Setting__c.getInstance();

Decimal rate =
    discount.Global_Rate__c;

How interviewers ask it“Explain CRUD and FLS in Apex in detail — what should a new team member understand about it?”

What is CRUD and FLS in Apex?

AdvancedSalesforce Apex
Quick answerCRUD permissions control user access to entire objects, while FLS permissions control user access to specific fields on those objects.
Java
if (
    Schema.sObjectType.Account.isCreateable()
    &&
    Schema.sObjectType.Account
        .fields.Rating.isCreateable()
) {

    insert new Account(
        Name = 'Protected Inc',
        Rating = 'Hot'
    );

}

How interviewers ask it“How would you explain some advanced SOQL techniques to a junior engineer, and what do people most often get wrong?”

What are some advanced SOQL techniques?

AdvancedSalesforce Apex
Quick answerAdvanced SOQL includes using aggregate functions ( COUNT(), SUM(), AVG() ), GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, and SOQL for loops to process large result sets efficiently.

Advanced SOQL includes using aggregate functions (COUNT(), SUM(), AVG()), GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, and SOQL for loops to process large result sets efficiently.

  • Aggregate queries: SELECT COUNT(Id) FROM Account
  • GROUP BY: SELECT Type, COUNT(Id) FROM Account GROUP BY Type
  • SOQL for loop: for (Account acc : [SELECT Id FROM Account])
  • Relationship queries: SELECT Name, (SELECT LastName FROM Contacts) FROM Account
  • Date literals: WHERE CreatedDate = TODAY
Java
// Aggregate query: count accounts by type
AggregateResult[] results = [
    SELECT Type, COUNT(Id) total
    FROM Account
    GROUP BY Type
];

for (AggregateResult ar : results) {
    System.debug('Type: ' + ar.get('Type') + ' Count: ' + ar.get('total'));
}

How interviewers ask it“Suppose you need to query parent-child relationships in SOQL — how do you approach it, and what can go wrong?”

How do you query parent-child relationships in SOQL?

AdvancedSalesforce Apex
Quick answerUse dot notation to traverse relationships. For parent-to-child, use a subquery inside the main query.
  • Parent-to-child: SELECT Name, (SELECT LastName FROM Contacts) FROM Account
  • Child-to-parent: SELECT Account.Name, LastName FROM Contact
  • Multiple levels: SELECT Account.Owner.Name FROM Contact
Java
// Parent-to-child subquery
List<Account> accountsWithContacts = [
    SELECT Name, (SELECT LastName FROM Contacts)
    FROM Account
    WHERE Id IN :accountIds
];

// Child-to-parent dot notation
List<Contact> contacts = [
    SELECT Account.Name, LastName
    FROM Contact
    WHERE AccountId IN :accountIds
];

How interviewers ask it“How would you explain advanced SOSL features to a junior engineer, and what do people most often get wrong?”

What are advanced SOSL features?

AdvancedSalesforce Apex
Quick answerSOSL supports searching across multiple objects, field‑specific search, fuzzy search, and returning snippets of matched text.
  • Search scope: FIND {searchTerm} IN ALL FIELDS
  • Returning specific fields: RETURNING Account(Name, Phone)
  • Search groups: FIND {searchTerm} IN NAME FIELDS RETURNING Contact
Java
// SOSL search across multiple objects
List<List<SObject>> searchResults = [
    FIND 'Acme*' IN ALL FIELDS
    RETURNING Account(Name, Phone), Contact(FirstName, LastName)
];

How interviewers ask it“Explain advanced DML operations in Apex in detail — what should a new team member understand about them?”

What are advanced DML operations?

AdvancedSalesforce Apex
Quick answerAdvanced DML includes Database class methods for partial success, upsert with external IDs, merge, and lead convert.
  • Database.insert(records, false) – allow partial success
  • upsert – insert or update based on external ID
  • merge – merge duplicate records
  • Database.convertLead – convert leads
Java
// Database.insert with partial success
Database.SaveResult[] srList = Database.insert(accountList, false);

for (Database.SaveResult sr : srList) {
    if (!sr.isSuccess()) {
        for (Database.Error err : sr.getErrors()) {
            System.debug(err.getMessage());
        }
    }
}

// Upsert using external ID
Account acc = new Account(Name = 'Upsert Corp', ExtId__c = 'EXT-001');
upsert acc ExtId__c;

How interviewers ask it“How would you explain best practices for writing triggers to a junior engineer, and what do people most often get wrong?”

What are best practices for writing triggers?

AdvancedSalesforce Apex
Quick answerBest practices include one trigger per object, bulkification, using trigger context variables correctly, avoiding SOQL/DML inside loops, and delegating logic to handler classes.
  • Single trigger per object
  • Bulkify – process collections, not single records
  • Use helper classes for business logic
  • Avoid SOQL in loops – use maps
  • Validate before DML – use addError
Java
// Best practice: one trigger per object, bulkified, using helper class
trigger AccountTrigger on Account (before insert, before update) {
    AccountHandler.handleTrigger(Trigger.old, Trigger.new, Trigger.oldMap, Trigger.newMap, Trigger.operationType);
}

How interviewers ask it“How would you explain the trigger handler pattern to a junior engineer, and what do people most often get wrong?”

What is the Trigger Handler pattern?

AdvancedSalesforce Apex
Quick answerThe Trigger Handler pattern is a design pattern where you centralize all trigger logic in a separate class (handler), making triggers lean and maintainable.
  • Handler class – contains methods for each trigger event
  • Trigger – only calls the handler
  • Testable – handler logic can be unit‑tested independently
Java
// Handler class for trigger logic
public class AccountHandler {
    public static void handleTrigger(List<Account> oldList, List<Account> newList, Map<Id, Account> oldMap, Map<Id, Account> newMap, System.TriggerOperation op) {
        if (op == System.TriggerOperation.BEFORE_INSERT) {
            validateAccounts(newList);
        } else if (op == System.TriggerOperation.BEFORE_UPDATE) {
            validateAccounts(newList);
        }
    }
    private static void validateAccounts(List<Account> accs) {
        for (Account a : accs) {
            if (a.Name == null) a.Name.addError('Name required');
        }
    }
}

How interviewers ask it“Suppose you need to prevent SOQL injection in Apex — how do you approach it, and what can go wrong?”

How do you prevent SOQL injection?

AdvancedSalesforce Apex
Quick answerUse bind variables ( :variable) in dynamic SOQL instead of concatenating strings.

Use bind variables (:variable) in dynamic SOQL instead of concatenating strings.

  • Bind variables: Database.query('SELECT Id FROM Account WHERE Name = :name')
  • Escape special characters – avoid raw string concatenation
  • Use with sharing to enforce security
Java
// Using bind variables prevents injection
String searchName = 'Acme';
List<Account> accounts = Database.query('SELECT Id FROM Account WHERE Name = :searchName');

How interviewers ask it“Explain advanced batch Apex techniques in detail — what should a new team member understand about them?”

What are advanced Batch Apex techniques?

AdvancedSalesforce Apex
Quick answerAdvanced techniques include stateful batch (using Database.Stateful ), chaining batch jobs, and using start() to query large datasets.

Advanced techniques include stateful batch (using Database.Stateful), chaining batch jobs, and using start() to query large datasets.

  • Stateful – maintain instance variables across chunks
  • Chain – call Database.executeBatch(nextJob) in finish()
  • Scope – set scope parameter for chunk size
Java
// Stateful batch example
global class StatefulBatch implements Database.Batchable<sObject>, Database.Stateful {
    global Integer recordCount = 0;
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id FROM Account');
    }
    global void execute(Database.BatchableContext bc, List<Account> scope) {
        recordCount += scope.size();
    }
    global void finish(Database.BatchableContext bc) {
        System.debug('Total processed: ' + recordCount);
    }
}

How interviewers ask it“Suppose you need to chain Queueable jobs in Apex — how do you approach it, and what can go wrong?”

How do you chain Queueable jobs?

AdvancedSalesforce Apex
Quick answerUse System.enqueueJob inside the execute method to chain another Queueable job.
  • Chain: System.enqueueJob(new SecondQueueable());
  • Monitor: AsyncApexJob to track status
Java
public class FirstQueueable implements Queueable {
    public void execute(QueueableContext ctx) {
        // do work
        System.enqueueJob(new SecondQueueable());
    }
}

How interviewers ask it“Suppose you need to schedule Apex classes dynamically — how do you approach it, and what can go wrong?”

How do you schedule Apex classes dynamically?

AdvancedSalesforce Apex
Quick answerUse System.schedule with a cron expression to schedule a class implementing Schedulable.
  • Cron expression: '0 0 2 * * ?' – daily at 2 AM
  • Schedule: System.schedule('Job Name', cronExp, new MySchedulable());
  • Manage: CronTrigger to view scheduled jobs
Java
// Schedule a job dynamically
String cronExp = '0 0 2 * * ?'; // 2 AM daily
System.schedule('Daily Cleanup', cronExp, new CleanupScheduler());

How interviewers ask it“How would you explain common assertions used in Apex tests to a junior engineer, and what do people most often get wrong?”

What are common assertions used in Apex tests?

AdvancedSalesforce Apex
Quick answerUse System.assertEquals, System.assertNotEquals, System.assert, and System.assertThrows to validate expected behavior.
  • assertEquals: System.assertEquals(expected, actual)
  • assertNotEquals: System.assertNotEquals(expected, actual)
  • assert: System.assert(condition)
  • assertThrows: System.assertThrows(Exception.class, () => { ... })
Java
@isTest
static void testMethod() {
    Integer expected = 5;
    Integer actual = someMethod();
    System.assertEquals(expected, actual, 'Values should match');
    System.assertNotEquals(0, actual);
    System.assert(actual > 0);
    System.assertThrows(Exception.class, () => { throw new Exception('test'); });
}

How interviewers ask it“Walk me through a test data factory pattern in Apex. Where does it come up in real systems?”

What is a Test Data Factory pattern?

AdvancedSalesforce Apex
Quick answerA Test Data Factory is a reusable class that creates test data (records) with consistent defaults, making tests easier to write and maintain.
  • Factory class – static methods to create sObjects
  • Consistency – ensures valid data for tests
  • Reusability – share across test classes
Java
@isTest
public class TestDataFactory {
    public static Account createAccount(String name) {
        return new Account(Name = name);
    }
    public static List<Contact> createContacts(Integer count, Id accountId) {
        List<Contact> cons = new List<Contact>();
        for (Integer i = 0; i < count; i++) {
            cons.add(new Contact(LastName = 'Test' + i, AccountId = accountId));
        }
        return cons;
    }
}
AdvancedSalesforce Apex
Quick answerIt allows a test method to access all org data, not just test data. Use sparingly – it makes tests less isolated and more fragile.
  • Default: tests see only data created in test context
  • When to use: when you need reference data that cannot be created in tests
  • Drawback: can cause flaky tests if org data changes
Java
@isTest(SeeAllData=true)
static void testWithAllData() {
    // This test can see real org data
    // Use sparingly
}

How interviewers ask it“How would you enforce CRUD and FLS? Walk me through your approach.”

How do you enforce CRUD and FLS in Apex?

AdvancedSalesforce Apex
Quick answerUse Schema.sObjectType methods like isCreateable(), isReadable(), etc., to check permissions before performing DML or queries.
  • CRUD: Schema.Account.isAccessible()
  • FLS: Schema.Account.Name.isAccessible()
  • Without Sharing bypasses these checks – handle with care
Java
if (Schema.sObjectType.Account.isCreateable() &&
    Schema.sObjectType.Account.fields.Name.isCreateable()) {
    insert new Account(Name = 'Safe');
}

How interviewers ask it“How is `with sharing` different from `without sharing`, and when does the difference matter in practice?”

What is the difference between `with sharing` and `without sharing`?

AdvancedSalesforce Apex
Quick answerwith sharing enforces the user's sharing rules; without sharing runs in system mode, ignoring sharing rules.
  • with sharing – respects record-level access
  • without sharing – bypasses sharing, used for administrative operations
  • Inherited sharing – uses sharing rules of the calling class
Java
public with sharing class SharingClass {
    // enforces sharing rules
}
public without sharing class SystemClass {
    // bypasses sharing
}
public inherited sharing class InheritedClass {
    // inherits from caller
}

How interviewers ask it“Suppose you need to make HTTP callouts in Apex — how do you approach it, and what can go wrong?”

How do you make HTTP callouts in Apex?

AdvancedSalesforce Apex
Quick answerUse Http, HttpRequest, and HttpResponse classes to send HTTP requests to external services.
  • Create request: HttpRequest req = new HttpRequest();
  • Set endpoint: req.setEndpoint('https://api.example.com');
  • Set method: req.setMethod('GET');
  • Send: HttpResponse res = new Http().send(req);
  • Handle response: res.getStatusCode(), res.getBody()
Java
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/data');
req.setMethod('GET');
req.setHeader('Content-Type', 'application/json');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
    String body = res.getBody();
}

How interviewers ask it“How would you test HTTP callouts? Walk me through your approach.”

How do you test HTTP callouts?

AdvancedSalesforce Apex
Quick answerUse HttpCalloutMock to mock the callout response in tests.
  • Implement: class MyMock implements HttpCalloutMock
  • Response: return new HttpResponse();
  • Set: Test.setMock(HttpCalloutMock.class, new MyMock());
Java
@isTest
class MyMock implements HttpCalloutMock {
    public HttpResponse respond(HttpRequest req) {
        HttpResponse res = new HttpResponse();
        res.setStatusCode(200);
        res.setBody('{"status":"ok"}');
        return res;
    }
}

@isTest
static void testCallout() {
    Test.setMock(HttpCalloutMock.class, new MyMock());
    // call your method that does callout
}

How interviewers ask it“How would you expose Apex as a REST API? Walk me through your approach.”

How do you expose Apex as a REST API?

AdvancedSalesforce Apex
Quick answerUse the @RestResource annotation to define a REST service, with methods annotated @HttpGet, @HttpPost, etc.
  • Class: @RestResource(urlMapping='/myresource/*')
  • GET: @HttpGet – retrieve data
  • POST: @HttpPost – create records
  • Request/Response: RestContext.request, RestContext.response
Java
@RestResource(urlMapping='/myresource/*')
global class MyRestResource {
    @HttpGet
    global static List<Account> getAccounts() {
        return [SELECT Id, Name FROM Account LIMIT 10];
    }
    @HttpPost
    global static String createAccount(String name) {
        Account a = new Account(Name = name);
        insert a;
        return a.Id;
    }
}

How interviewers ask it“Explain `@RemoteAction` in Apex in detail — what should a new team member understand about it?”

What is `@RemoteAction` in Apex?

AdvancedSalesforce Apex
Quick answer@RemoteAction allows Visualforce pages (and JavaScript) to call Apex methods asynchronously via JavaScript remoting.
  • Annotation: @RemoteAction on a static method
  • Client‑side: Visualforce.remoting.Manager.invokeAction
  • Alternatives: LWC uses @AuraEnabled instead
Java
public class RemoteActionExample {
    @RemoteAction
    public static String sayHello(String name) {
        return 'Hello ' + name;
    }
}

How interviewers ask it“Suppose you need to publish Platform Events in Apex — how do you approach it, and what can go wrong?”

How do you publish Platform Events in Apex?

AdvancedSalesforce Apex
Quick answerUse EventBus.publish to send a platform event. The event must be defined as a custom object with the __e suffix.
  • Create event: My_Event__e evt = new My_Event__e(Field__c = 'value');
  • Publish: EventBus.publish(evt);
  • Subscribe: @AuraEnabled or trigger on the event
Java
My_Event__e evt = new My_Event__e(Message__c = 'Hello');
EventBus.publish(evt);
AdvancedSalesforce Apex
Quick answerCDC captures changes to records and exposes them via Platform Events. Apex can listen to CDC events using triggers on the associated event object.
  • Event object: AccountChangeEvent for Account changes
  • Trigger: trigger on AccountChangeEvent
  • Use cases: real‑time integration, auditing
Java
trigger AccountChangeTrigger on AccountChangeEvent (after insert) {
    for (AccountChangeEvent evt : Trigger.new) {
        // process change event
    }
}

How interviewers ask it“Can you compare custom settings and custom metadata types? Where do people usually confuse them?”

What is the difference between Custom Settings and Custom Metadata Types?

AdvancedSalesforce Apex
Quick answerCustom Settings are per‑user or per‑org data stored in memory; Custom Metadata Types are deployable configuration that can be packaged and is read‑only at runtime.
  • Custom Settings: editable in UI, per‑user/org, cached
  • Custom Metadata: packaged, deployable, org‑wide, not editable at runtime
  • Performance: both are cached, but Custom Metadata is read‑only and more static
Java
// Custom Setting
Decimal rate = CustomSetting__c.getInstance().Rate__c;

// Custom Metadata
App_Config__mdt config = App_Config__mdt.getInstance('Global');
Boolean enabled = config.Is_Active__c;

How interviewers ask it“How would you send emails from Apex? Walk me through your approach.”

How do you send emails from Apex?

AdvancedSalesforce Apex
Quick answerUse Messaging.SingleEmailMessage for simple emails, or Messaging.sendEmail for mass emails.
  • Single: Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  • Set fields: mail.setToAddresses(['email@example.com']);
  • Send: Messaging.sendEmail(new Messaging.Email[] { mail });
  • Email Template: use setTemplateId to use a Visualforce or HTML email template
Java
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] { 'user@example.com' });
mail.setSubject('Hello');
mail.setPlainTextBody('Body text');
Messaging.sendEmail(new Messaging.Email[] { mail });

How interviewers ask it“Suppose you need to work with Attachments or ContentVersion — how do you approach it, and what can go wrong?”

How do you work with Attachments or ContentVersion in Apex?

AdvancedSalesforce Apex
Quick answerUse ContentVersion (Files) for modern document management. Insert a ContentVersion record and link it to a parent record via ContentDocumentLink.
  • ContentVersion: ContentVersion cv = new ContentVersion(ContentLocation = 'S', PathOnClient = 'file.pdf', ...);
  • Insert: insert cv;
  • Link: ContentDocumentLink cdl = new ContentDocumentLink(LinkedEntityId = parentId, ContentDocumentId = cv.ContentDocumentId);
Java
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S'; // stored in Salesforce
cv.PathOnClient = 'file.pdf';
cv.Title = 'My File';
cv.VersionData = Blob.valueOf('File content');
insert cv;

// Link to parent
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.LinkedEntityId = parentRecordId;
cdl.ContentDocumentId = cv.ContentDocumentId;
insert cdl;
AdvancedSalesforce Apex
Quick answerA SOQL for loop automatically queries records in batches of 200, preventing heap size errors when processing large datasets.
  • Syntax: for (Account acc : [SELECT Id FROM Account])
  • Optimization: uses internal query locator to avoid bulk memory usage
  • Best practice: use for DML on large sets
Java
// Processes in batches of 200
for (Account acc : [SELECT Id, Name FROM Account WHERE CreatedDate = TODAY]) {
    // Do something with each account
}
AdvancedSalesforce Apex
Quick answerAggregate queries use functions like COUNT(), SUM(), AVG(), MIN(), MAX() to summarize data. They are ideal for reports and dashboards.
  • Example: SELECT Type, COUNT(Id) FROM Account GROUP BY Type
  • Group by: use GROUP BY for category summaries
  • Having: HAVING COUNT(Id) > 10
Java
AggregateResult[] res = [
    SELECT Account.Type, COUNT(Id) total
    FROM Account
    GROUP BY Account.Type
    HAVING COUNT(Id) > 5
];

How interviewers ask it“Walk me through dynamic DML in Apex. Where does it come up in real systems?”

What is Dynamic DML?

AdvancedSalesforce Apex
Quick answerDynamic DML uses Database.insert, Database.update, etc., with the SObject type and field names as strings, allowing runtime flexibility.
  • Use: when object/field names are not known at compile time
  • Example: Database.insert(new SObject('Account'));
  • Drawback: loses compile‑time type safety
Java
// Dynamic DML with SObject type
SObject sobj = Schema.getGlobalDescribe().get('Account').newSObject();
sobj.put('Name', 'Dynamic Account');
Database.insert(sobj);
AdvancedSalesforce Apex
Quick answerIt returns a map of all SObject types accessible to the user. Used for dynamic code that needs to discover objects and fields at runtime.
  • Usage: Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
  • Check object existence: gd.containsKey('Account')
  • Performance: call sparingly, as it's expensive
Java
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
if (gd.containsKey('Account')) {
    Schema.DescribeSObjectResult dsr = gd.get('Account').getDescribe();
    System.debug('Account fields: ' + dsr.fields.getMap().keySet());
}

How interviewers ask it“Walk me through a query locator in batch Apex. Where does it come up in real systems?”

What is a Query Locator in Batch Apex?

AdvancedSalesforce Apex
Quick answerThe Database.QueryLocator is used in the start() method of a batch class to define the scope of records to be processed. It allows large datasets to be processed in chunks.
  • Return type: Database.QueryLocator
  • Usage: return Database.getQueryLocator('SELECT Id FROM Account');
  • Optimization: efficiently handles large query results
Java
global Database.QueryLocator start(Database.BatchableContext bc) {
    return Database.getQueryLocator('SELECT Id FROM Account WHERE CreatedDate = TODAY');
}
AdvancedSalesforce Apex
Quick answerIt marks a batch class as stateful, allowing instance variables to retain their values across chunk executions. Useful for accumulating totals or counters.
  • Annotation: global class MyBatch implements Database.Batchable<sObject>, Database.Stateful
  • Use case: counting total records processed across all chunks
  • Caution: state can be large and cause heap issues
Java
global class MyBatch implements Database.Batchable<sObject>, Database.Stateful {
    global Integer total = 0;
    // ...
    global void execute(Database.BatchableContext bc, List<sObject> scope) {
        total += scope.size();
    }
    // total is preserved across chunks
}
AdvancedSalesforce Apex
Quick answerYes. You can specify without sharing on the Queueable class to bypass sharing rules, or with sharing to enforce them.
  • Default: if not specified, uses sharing rules of the calling context
  • Override: explicitly declare public without sharing class MyQueueable
  • Best practice: explicitly define to avoid surprises
Java
public without sharing class MyQueueable implements Queueable {
    public void execute(QueueableContext ctx) {
        // runs in system mode
    }
}

How interviewers ask it“Suppose you need to create a custom exception in Apex — how do you approach it, and what can go wrong?”

How do you create a custom exception in Apex?

AdvancedSalesforce Apex
Quick answerDefine a class that extends Exception. Then throw it using throw new MyException('message');
  • Definition: class MyException extends Exception {}
  • Throw: throw new MyException('Error occurred');
  • Catch: catch (MyException e) { ... }
Java
public class MyException extends Exception {}
// throw new MyException('Something went wrong');

How interviewers ask it“Suppose you need to debug Apex code — how do you approach it, and what can go wrong?”

How do you debug Apex code?

AdvancedSalesforce Apex
Quick answerUse System.debug statements, check debug logs in the Developer Console, and use checkpoints or Apex debugger.
  • System.debug: System.debug('Value: ' + variable);
  • Log levels: System.debug(LoggingLevel.INFO, 'message');
  • Developer Console: execute anonymous, query editor, and logs
Java
System.debug(LoggingLevel.INFO, 'Variable value: ' + myVar);
// Check debug logs in Developer Console

How interviewers ask it“Walk me through some performance best practices in Apex. Where do they come up in real systems?”

What are some performance best practices in Apex?

AdvancedSalesforce Apex
Quick answerMinimize SOQL queries, avoid DML in loops, use collections, bulkify code, and leverage batch/queueable for large operations.
  • SOQL: query outside loops; use maps to avoid repeated queries
  • DML: use collections, not single records
  • Bulkification: design for multirecord operations
  • Asynchronous: use future/queueable/batch for heavy lifting
Java
// BAD: SOQL in loop
// for (Account a : accounts) {
//     List<Contact> cons = [SELECT Id FROM Contact WHERE AccountId = :a.Id];
// }

// GOOD: bulk query
Set<Id> accIds = new Map<Id, Account>(accounts).keySet();
Map<Id, List<Contact>> contactMap = new Map<Id, List<Contact>>();
for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accIds]) {
    if (!contactMap.containsKey(c.AccountId)) contactMap.put(c.AccountId, new List<Contact>());
    contactMap.get(c.AccountId).add(c);
}

How interviewers ask it“Why is it bad to have SOQL inside a loop — and how does that matter in practice?”

Why is it bad to have SOQL inside a loop?

AdvancedSalesforce Apex
Quick answerIt causes multiple SOQL queries, quickly hitting governor limits. Always extract data beforehand and use maps for lookups.
  • Problem: each iteration consumes a query
  • Fix: query once, store in map, then iterate
  • Governor limit: max 100 SOQL queries per transaction
Java
// BAD: query inside loop
for (Account a : Trigger.new) {
    List<Contact> cons = [SELECT Id FROM Contact WHERE AccountId = :a.Id];
}

// GOOD: query once, use map
Set<Id> accIds = new Map<Id, Account>(Trigger.new).keySet();
List<Contact> allContacts = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accIds];
Map<Id, List<Contact>> contactsByAcc = new Map<Id, List<Contact>>();
for (Contact c : allContacts) {
    if (!contactsByAcc.containsKey(c.AccountId)) contactsByAcc.put(c.AccountId, new List<Contact>());
    contactsByAcc.get(c.AccountId).add(c);
}

How interviewers ask it“How would you use maps for efficient lookups? Walk me through your approach.”

How do you use maps for efficient lookups?

AdvancedSalesforce Apex
Quick answerQuery related records once, put them into a map keyed by the lookup field, then retrieve in a loop.
  • Example: Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id FROM Account]);
  • Usage: Account acc = accountMap.get(contact.AccountId);
  • Benefit: O(1) lookups, no extra queries
Java
Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Name FROM Account WHERE Id IN :accountIds]);
for (Contact c : contacts) {
    Account acc = accountMap.get(c.AccountId);
    // use acc
}

How interviewers ask it“Why avoid DML inside loops — and how does that matter in practice?”

Why avoid DML inside loops?

AdvancedSalesforce Apex
Quick answerDML statements inside loops cause multiple DML operations, consuming governor limits quickly and reducing performance.
  • Problem: each iteration is a separate DML call
  • Fix: collect records in a list and DML outside the loop
  • Governor limit: max 150 DML statements per transaction
Java
// BAD: DML inside loop
for (Account a : accounts) {
    update a;
}

// GOOD: collect in list
List<Account> toUpdate = new List<Account>();
for (Account a : accounts) {
    toUpdate.add(a);
}
update toUpdate;

How interviewers ask it“Walk me through some bulkification patterns in Apex. Where do they come up in real systems?”

What are some bulkification patterns?

AdvancedSalesforce Apex
Quick answerUse maps for lookups, sets for distinct values, and lists for DML operations. Process data in collections rather than individual records.
  • Pattern 1: collect IDs in set, query once
  • Pattern 2: use map to store related records
  • Pattern 3: accumulate records in list, DML once
Java
// Use set for distinct IDs
Set<Id> ids = new Set<Id>();
for (Account a : accounts) ids.add(a.Id);

// Use map for lookups
Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id FROM Account]);

// Use list for DML
List<Contact> toInsert = new List<Contact>();
// fill list
insert toInsert;
AdvancedSalesforce Apex
Quick answerYes, but it's not recommended. Best practice is one trigger per object, with logic delegated to handler classes.
  • Why one? – avoids unpredictable execution order
  • If multiple: order is not guaranteed
  • Best practice: single trigger, handler pattern
Java
// Not recommended to have multiple triggers
// Best: one trigger per object
// Trigger on Account (before insert)
trigger AccountTrigger on Account (before insert) {
    AccountHandler.handleInsert(Trigger.new);
}

How interviewers ask it“How would you explain the order of execution in a trigger to a junior engineer, and what do people most often get wrong?”

What is the order of execution in a trigger?

AdvancedSalesforce Apex
Quick answerOrder: Before triggers, After triggers, Assignment rules, Auto‑response rules, Workflow rules, Process Builder, Escalation rules, and finally Commit.
  • Before insert/update – modify fields before saving
  • After insert/update – use updated record IDs for related operations
  • System order: see Salesforce docs for full sequence
Java
// Order: Before triggers → After triggers → Assignment rules → Auto-response → Workflow → Process Builder → Escalation → Commit.
// Example showing before/after usage
trigger OrderTrigger on Order (before insert, after insert) {
    if (Trigger.isBefore) {
        // modify fields
    } else if (Trigger.isAfter) {
        // create related records
    }
}

How interviewers ask it“How would you explain the main trigger context variables to a junior engineer, and what do people most often get wrong?”

What are the main trigger context variables?

AdvancedSalesforce Apex
Quick answerTrigger.new – new records (before/after insert, after update) Trigger.old – old records (before/after update, before delete) Trigger.newMap – map of new records by ID (after insert, after update) Trigger.oldMap – map of old records by ID (before update, before delete) Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isUndelete
  • Trigger.new – new records (before/after insert, after update)
  • Trigger.old – old records (before/after update, before delete)
  • Trigger.newMap – map of new records by ID (after insert, after update)
  • Trigger.oldMap – map of old records by ID (before update, before delete)
  • Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isUndelete
Java
// Trigger.new - new records
// Trigger.old - old records
// Trigger.newMap - map of new by Id
// Trigger.oldMap - map of old by Id
// Trigger.isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter
if (Trigger.isInsert && Trigger.isBefore) {
    for (Account a : Trigger.new) {
        a.Name = a.Name.toUpperCase();
    }
}

How interviewers ask it“How would you prevent record saving in a trigger? Walk me through your approach.”

How do you prevent record saving in a trigger?

AdvancedSalesforce Apex
Quick answerUse addError on a record or on a field to prevent the DML operation and display a user‑friendly error message.
  • Record error: record.addError('Invalid data');
  • Field error: record.fieldName.addError('Invalid value');
  • Works in before/after triggers
Java
if (Trigger.isBefore) {
    for (Account a : Trigger.new) {
        if (a.Name == null) {
            a.Name.addError('Name cannot be null');
        }
        // field-level error
        if (a.Industry == null) {
            a.Industry.addError('Industry required');
        }
    }
}
AdvancedSalesforce Apex
Quick answerBefore triggers are used to modify field values before they are saved. After triggers are used when you need the record ID (e.g., for creating related records).
  • Before: validation, field updates, cross‑object calculations
  • After: creating child records, sending emails, updating external systems
Java
// Before: modify fields before save
// After: need record IDs, create related records
trigger ContactTrigger on Contact (before insert) {
    for (Contact c : Trigger.new) {
        c.Description = 'New';
    }
}
trigger AccountTrigger on Account (after insert) {
    for (Account a : Trigger.new) {
        // Create a default contact using the new Account Id
        insert new Contact(LastName = 'Default', AccountId = a.Id);
    }
}

How interviewers ask it“Walk me through a trigger framework in Apex. Where does it come up in real systems?”

What is a Trigger Framework?

AdvancedSalesforce Apex
Quick answerA trigger framework is a structured approach (often using a base class) to handle trigger events, enforce order, and improve maintainability.
  • Base class – handles trigger context variables and event dispatching
  • Handler classes – implement specific logic for each event
  • Benefits: consistent pattern, easier testing, less code duplication
Java
// Base trigger framework (simplified)
public abstract class TriggerHandler {
    public static void run() {
        // handle context, invoke specific handlers
    }
}
// Then each trigger calls TriggerHandler.run();

How interviewers ask it“Walk me through the minimum code coverage required for deployment in Apex. Where does it come up in real systems?”

What is the minimum code coverage required for deployment?

AdvancedSalesforce Apex
Quick answerSalesforce requires at least 75% overall code coverage for Apex classes and triggers to be deployed to production. Triggers must have 1% coverage on their own.
  • Overall: 75% of all Apex code must be covered
  • Triggers: must have at least 1% coverage
  • Best practice: aim for 100% to avoid deployment issues
Java
// Minimum 75% overall coverage
// Triggers need at least 1% coverage
// Write test classes to cover all logic
@isTest
class MyTest {
    @isTest static void testMethod() {
        // cover code
    }
}

How interviewers ask it“How would you isolate test data? Walk me through your approach.”

How do you isolate test data?

AdvancedSalesforce Apex
Quick answerUse @IsTest annotations and the Test class methods like Test.startTest() and Test.stopTest() to create test data that is automatically rolled back.
  • Test.startTest() – resets governor limits for the code block
  • Test.stopTest() – executes asynchronous calls
  • Data isolation: test data doesn't commit to the org
Java
@isTest
static void testIsolation() {
    Test.startTest();
    // perform DML, async calls
    Test.stopTest(); // executes async code
    // assertions after
}

How interviewers ask it“Explain mock frameworks in Apex testing in detail — what should a new team member understand about them?”

What are mock frameworks in Apex testing?

AdvancedSalesforce Apex
Quick answerMock frameworks like stub (using System.StubProvider) allow you to create test doubles for dependencies, isolating the class under test.
  • Stub: implement System.StubProvider to return mock data
  • Test.setMock: used for HTTP callouts and other external dependencies
  • Benefits: fast, reliable, isolated unit tests
Java
// Using StubProvider (example)
public class MyMock implements System.StubProvider {
    public Object handleMethodCall(Object stubbedObject, String stubbedMethodName, Type returnType, List<Type> listOfParamTypes, List<String> listOfParamNames, List<Object> listOfArgs) {
        if (stubbedMethodName == 'getData') {
            return 'Mock Data';
        }
        return null;
    }
}
// Use Test.createStub() to apply
AdvancedSalesforce Apex
Quick answerNo, directly calling out from a trigger is not allowed. Instead, you must call a @future or Queueable method that performs the callout.
  • Why? – triggers are synchronous, callouts require async
  • Solution: use @future(callout=true) or Queueable
  • Best practice: use Queueable for better monitoring
Java
// In trigger, call a future method
@future(callout=true)
public static void doCallout(String param) {
    // make callout
}
// Trigger: MyClass.doCallout('test');

How interviewers ask it“Walk me through the top 5 Apex best practices. Where do they come up in real systems?”

What are the top 5 Apex best practices?

AdvancedSalesforce Apex
Quick answer1. Bulkify – always design for multirecord operations. 2. Avoid SOQL/DML in loops – use maps and collections. 3. Use with sharing unless you have a strong reason not to. 4. Handle exceptions – try-catch and addError where appropriate. 5. Write test classes – aim for 100% coverage and use data factories.

1. Bulkify – always design for multirecord operations.
2. Avoid SOQL/DML in loops – use maps and collections.
3. Use with sharing unless you have a strong reason not to.
4. Handle exceptions – try-catch and addError where appropriate.
5. Write test classes – aim for 100% coverage and use data factories.

Java
// Top 5 best practices summarized:
// 1. Bulkify – process collections, not single records.
// 2. Avoid SOQL/DML in loops – use maps and sets.
// 3. Use with sharing (unless system mode needed).
// 4. Handle exceptions properly (try-catch, addError).
// 5. Write comprehensive test classes (>=75% coverage).

Salesforce Apex Coding Interview Questions (Programs with Code)

10 questions

Hands-on Salesforce Apex programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.

How interviewers ask it“Show me batch Apex structure — write it out and explain each step as you go.”

Explain batch Apex structure in Salesforce Apex with an example.

CodingSalesforce Apex
Java
global class MyBatch
    implements Database.Batchable<SObject> {

    global Database.QueryLocator start(
        Database.BatchableContext BC
    ) {

        return Database.getQueryLocator(
            'SELECT Id FROM Account'
        );

    }

    global void execute(
        Database.BatchableContext BC,
        List<Account> scope
    ) {

        // Batch chunks executed here

    }

    global void finish(
        Database.BatchableContext BC
    ) {

        // Cleanup actions

    }

}

Practise with the free Salesforce Apex quiz

Multiple-choice questions with instant feedback. Takes about 10 minutes and shows exactly which concepts to revise.

Start the Salesforce Apex quiz →

Salesforce Apex interview FAQ

What is Salesforce Apex?
Apex is Salesforce's strongly typed, object-oriented programming language used to develop custom business logic on the Salesforce platform.
What are Apex Triggers?
Apex Triggers are code that execute automatically before or after database events such as insert, update, delete, or undelete operations.
What is SOQL?
SOQL (Salesforce Object Query Language) is used to retrieve records from Salesforce objects in Apex and other Salesforce applications.
What is SOSL?
SOSL (Salesforce Object Search Language) is used to search text across multiple Salesforce objects simultaneously.
What are Governor Limits?
Governor Limits are Salesforce-enforced limits that ensure efficient resource usage in a multi-tenant environment.
What is Batch Apex?
Batch Apex processes large numbers of Salesforce records asynchronously by dividing them into manageable batches.
What is Queueable Apex?
Queueable Apex allows asynchronous processing with support for complex objects and job chaining.
What are Future Methods in Apex?
Future Methods execute Apex code asynchronously in the background for long-running operations such as web service callouts.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.