Salesforce Apex interview questions commonly test language fundamentals, transaction behavior, governor limits, bulk processing, triggers, SOQL, DML, asynchronous Apex, security, exception handling, and test design. Candidates are also expected to explain how they would solve realistic Salesforce scenarios rather than only define Apex terms.

The questions and answers below cover Apex concepts for freshers and experienced developers, followed by scenario-based questions that are useful for interviews requiring practical coding and design decisions.

Salesforce Apex fundamentals interview questions

What is Apex?

Apex is a strongly typed, object-oriented programming language used on the Salesforce Platform. Developers use Apex to implement server-side business logic that cannot be handled completely through declarative tools.

Apex can run when records are inserted, updated, deleted, or undeleted, when a user invokes a custom action, when an integration calls an Apex service, or when scheduled and asynchronous jobs execute.

How does Apex work on the Salesforce Platform?

Apex code is compiled and stored as metadata on the Salesforce Platform. When an event invokes the code, the Apex runtime executes it within a transaction and enforces platform rules such as sharing, data access, and governor limits.

An Apex transaction can begin from a trigger, a Lightning component request, an API call, a scheduled job, a batch job, a queueable job, a Visualforce controller, or another supported entry point. The transaction either commits its successful database changes or rolls them back when an unhandled exception occurs.

When an end user triggers Apex execution by saving a record, clicking a custom action, or accessing a Visualforce page, Salesforce retrieves and runs the compiled instructions through the Apex runtime.

When should a Salesforce developer use Apex?

Use Apex when a requirement needs programmatic logic that is difficult or unsuitable to implement with Flow, validation rules, approval processes, formulas, or other declarative tools.

  • Applying complex validation across multiple related objects.
  • Processing large collections of records with controlled transaction logic.
  • Creating trigger logic for record events.
  • Implementing REST or SOAP web services.
  • Calling external services through HTTP callouts.
  • Running scheduled, batch, queueable, or future processing.
  • Creating custom controllers and service classes.
  • Building reusable domain, selector, and application service logic.
  • Implementing custom transactional behavior not supported by workflows or Flow.

What are the main Apex programming elements?

An Apex program can contain classes, interfaces, variables, constants, data types, expressions, operators, conditional statements, loops, collections, methods, constructors, exceptions, SOQL queries, SOSL searches, and DML operations.

How are comments written in Apex?

  • Single-line comment: Starts with //.
  • Block comment: Starts with /* and ends with */.
</>
Copy
// Single-line comment

/*
Multi-line comment
*/

Apex control statements and loop interview questions

What is a do-while loop in Apex?

A do-while loop executes its body at least once because the condition is evaluated after the loop body.

</>
Copy
do
{
Statement1;
Statement2;
}
While(Exp1);
Statement3;

What is a while loop in Apex?

A while loop checks its condition before each iteration. The body may not execute if the condition is false initially.

</>
Copy
While(condition1)
{
Statement1;
Statement2;
}
Statement3;

What is a for loop in Apex?

A standard for loop contains an initialization expression, a condition, and an increment expression. Apex also supports collection-based for loops and SOQL for loops.

</>
Copy
for(expresson1,expresson2,expresson3)
{
Statement1;
Statement2;
}
Statement3;
</>
Copy
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 100];

for (Account accountRecord : accounts) {
    System.debug(accountRecord.Name);
}

What is a SOQL for loop, and why is it useful?

A SOQL for loop iterates over query results without requiring the developer to store the entire result set in a separate list first. It is useful when processing many records because Salesforce retrieves query results in manageable batches.

</>
Copy
for (Contact contactRecord : [
    SELECT Id, Email
    FROM Contact
    WHERE Email != null
]) {
    System.debug(contactRecord.Email);
}

Apex classes, variables, constructors, and methods

How can a developer view System.debug() results?

System.debug() messages appear in Salesforce debug logs when the relevant user or automated process has an active trace flag. In Lightning Experience, open Setup, search for Debug Logs, add or update a trace flag, execute the process, and then open the generated log.

The Developer Console and supported Salesforce development tools can also display logs. Developers should set appropriate log levels and remove unnecessary debug statements from production code because large logs are difficult to inspect and may expose sensitive values.

What is the difference between an Apex constructor and a method?

ConstructorMethod
Has the same name as the class.Can have any valid method name.
Runs when an instance of the class is created.Runs only when it is called.
Does not declare a return type.Declares a return type or uses void.
Initializes the state of an object.Performs an operation or returns a value.
Can accept parameters.Can accept parameters.
Cannot be declared static.Can be instance-based or static.
Is not inherited as a callable constructor by a subclass.Can be inherited and may be overridden when permitted.
A no-argument constructor is available implicitly only when no constructor is declared.No method is added automatically when none is declared.

What are the different types of Apex variables?

  • Local variables: Declared inside a method, constructor, loop, or statement block and available only within that scope.
  • Instance variables: Belong to an object created from a class. Each object instance has its own values.
  • Static variables: Belong to the class for the duration of the current Apex transaction and are shared by instances in that transaction.

What types of methods can be written in Apex?

  • Instance methods.
  • Static methods.
  • Getter and setter methods.
  • Virtual methods.
  • Override methods.
  • Abstract methods.
  • Web service and REST resource methods.
  • Invocable methods used by Flow.
  • Asynchronous methods, including future, queueable, batch, and schedulable implementations.

When should an Apex method be declared final?

A final method cannot be overridden by a subclass. Declare a method final when subclasses must use the exact implementation and changing that behavior through inheritance would violate the class design.

When should an Apex method be declared abstract?

An abstract method defines a method signature without an implementation. It must be declared in an abstract class, and a concrete subclass must provide the implementation unless the subclass is also abstract.

When should an Apex method be declared virtual?

A virtual method provides a default implementation that a subclass may override. Use it when the base behavior is useful but controlled customization through inheritance is expected.

What is the difference between virtual, abstract, and override in Apex?

KeywordPurpose
virtualAllows a class or method with an implementation to be extended or overridden.
abstractDefines an incomplete class or a method without implementation that subclasses must complete.
overrideMarks a subclass method that replaces an inherited virtual or abstract method.

Apex collections and data handling interview questions

What are List, Set, and Map in Apex?

  • List: An ordered collection that can contain duplicate values.
  • Set: An unordered collection of unique values.
  • Map: A collection of key-value pairs in which each key is unique.
</>
Copy
List<String> accountNames = new List<String>{'Acme', 'Global Media'};
Set<Id> accountIds = new Set<Id>();
Map<Id, Account> accountsById = new Map<Id, Account>();

Why are Sets and Maps important in bulk Apex?

Sets help collect unique record IDs for a single SOQL query. Maps provide constant-time lookup by key, which avoids nested loops and repeated queries. They are fundamental to bulk-safe trigger and service logic.

What is an sObject in Apex?

An sObject is the Apex representation of a Salesforce record. Standard objects such as Account and custom objects such as Invoice__c are strongly typed sObjects. The generic sObject type can represent a record whose specific object type is determined at runtime.

What is the difference between an ID and an external ID?

A Salesforce record ID uniquely identifies a record within Salesforce. An external ID is a custom field marked for matching records with identifiers from another system. External IDs are commonly used with upsert operations and integrations.

SOQL, SOSL, and DML Apex interview questions

What is the difference between SOQL and SOSL?

SOQLSOSL
Queries records from one primary object and can traverse defined relationships.Searches text across multiple objects and fields.
Used when the target object and fields are known.Used when the search term is known but the matching object may vary.
Returns records grouped by the queried object.Returns lists of records grouped by object type.
Supports filtering, ordering, grouping, and aggregate queries.Supports text-search expressions and object-specific returning clauses.

What are DML statements in Apex?

DML statements modify Salesforce records. Common operations include insert, update, upsert, delete, undelete, and merge.

</>
Copy
List<Account> accountsToInsert = new List<Account>{
    new Account(Name = 'Acme'),
    new Account(Name = 'Global Media')
};

insert accountsToInsert;

What is the difference between DML statements and Database methods?

DML statements normally throw an exception when an operation fails. Database methods can use an allOrNone parameter and return result objects that allow the application to inspect individual record successes and failures.

</>
Copy
Database.SaveResult[] results = Database.insert(accountsToInsert, false);

for (Database.SaveResult result : results) {
    if (!result.isSuccess()) {
        for (Database.Error errorItem : result.getErrors()) {
            System.debug(errorItem.getMessage());
        }
    }
}

What is upsert in Apex?

Upsert inserts a record when no match exists and updates an existing record when a match is found. Matching can use the Salesforce record ID or a specified external ID field.

Can SOQL or DML be written inside an Apex loop?

It is syntactically possible, but it is normally a serious design error because each iteration can consume another query or DML statement. This can cause governor-limit failures when many records are processed. Collect values first, execute SOQL and DML outside the loop, and use Sets and Maps to connect the data.

Governor limits and bulkification interview questions

What are governor limits in Salesforce Apex?

Governor limits are runtime limits applied to Apex transactions in Salesforce’s multitenant environment. They restrict resources such as SOQL queries, DML statements, queried records, CPU time, heap size, and callouts.

A strong interview answer should explain that limits are measured per execution context and that synchronous and asynchronous contexts can have different limits. Developers should check current platform documentation rather than hard-code assumptions about every numeric limit.

What does bulkification mean in Apex?

Bulkification means designing code to process one record or many records with the same execution path. Bulkified code uses collections, performs queries outside loops, groups DML operations, and avoids assumptions that a trigger receives only one record.

How would you bulkify code that queries contacts for accounts?

Collect all Account IDs into a Set, run one Contact query using an IN filter, and group the returned contacts in a Map keyed by Account ID.

</>
Copy
Set<Id> accountIds = new Set<Id>();

for (Account accountRecord : Trigger.new) {
    accountIds.add(accountRecord.Id);
}

Map<Id, List<Contact>> contactsByAccountId = new Map<Id, List<Contact>>();

for (Contact contactRecord : [
    SELECT Id, AccountId, Email
    FROM Contact
    WHERE AccountId IN :accountIds
]) {
    if (!contactsByAccountId.containsKey(contactRecord.AccountId)) {
        contactsByAccountId.put(contactRecord.AccountId, new List<Contact>());
    }
    contactsByAccountId.get(contactRecord.AccountId).add(contactRecord);
}

How can an Apex developer monitor governor-limit usage?

The Limits class provides methods such as Limits.getQueries(), Limits.getLimitQueries(), Limits.getDmlStatements(), and corresponding limit methods. These are useful for diagnostics and tests, but they do not replace efficient design.

Salesforce trigger interview questions and answers

What is an Apex trigger?

An Apex trigger executes before or after database events on a Salesforce object. Supported events include insert, update, delete, and undelete, with event availability depending on whether the trigger runs before or after the operation.

What is the difference between before and after triggers?

  • Before trigger: Commonly used to validate or change values on records before Salesforce saves them. Fields on Trigger.new can generally be assigned directly in before insert and before update contexts.
  • After trigger: Used when logic requires record IDs, committed field values from the initial save stage, or creation and updates of related records.

What are Apex trigger context variables?

Trigger context variables identify the current event and provide access to the affected records. Common variables include Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isBefore, Trigger.isAfter, Trigger.new, Trigger.old, Trigger.newMap, and Trigger.oldMap.

Why should trigger logic be moved into a handler class?

A handler class keeps the trigger small, separates logic by event, improves testability, supports reuse, and makes recursion control and dependency management easier. A common design is one trigger per object with logic delegated to handler or service classes.

How can trigger recursion be controlled?

Recursion should first be prevented through idempotent logic and field-change checks. When a guard is required, a static Set or Map of processed record IDs is usually safer than a single static Boolean because one transaction may process several record groups.

Asynchronous Apex interview questions for experienced developers

What asynchronous processing options are available in Apex?

  • Future methods: Run simple asynchronous static methods.
  • Queueable Apex: Supports complex member variables, job IDs, and controlled job chaining.
  • Batch Apex: Processes large data volumes in separate execution batches.
  • Scheduled Apex: Runs Apex according to a defined schedule.
  • Platform events and event-driven processing: Decouple producers and consumers for supported asynchronous workflows.

What is the difference between future and Queueable Apex?

Future methods accept only supported primitive parameters or collections of primitives and provide limited job control. Queueable Apex implements the Queueable interface, can accept more complex state, returns a job ID when enqueued, and supports chaining within platform rules. Queueable Apex is generally preferred for new asynchronous application logic unless a future method specifically fits the requirement.

When should Batch Apex be used?

Use Batch Apex when a process must handle a data volume too large for one transaction. A batch class implements Database.Batchable and defines start, execute, and finish methods. Each execute scope runs as a separate transaction with its own governor-limit allocation.

Can an HTTP callout be made from Apex?

Yes. Apex can send HTTP requests by using classes such as Http, HttpRequest, and HttpResponse. Authentication and endpoint configuration should normally use Named Credentials or the applicable Salesforce credential features rather than hard-coded secrets.

Apex security and exception handling interview questions

What is the difference between with sharing, without sharing, and inherited sharing?

  • with sharing: Enforces record-level sharing rules for the running context.
  • without sharing: Does not enforce record-level sharing rules in the class, although object and field permissions still require deliberate enforcement.
  • inherited sharing: Uses the sharing mode of the caller and makes the intended behavior explicit.

These keywords control record-level sharing, not automatic object-level and field-level permission enforcement. Secure Apex must also consider CRUD, field-level security, user-mode operations where appropriate, and input validation.

How can CRUD and field-level security be enforced in Apex?

Depending on the operation and application design, developers can use user-mode database operations, security-enforced queries, Security.stripInaccessible(), and schema describe checks. The selected approach should handle both read and write access and should not rely only on page-layout visibility.

How are exceptions handled in Apex?

Apex uses try, catch, and finally blocks. Code should catch only exceptions it can handle meaningfully, preserve useful diagnostic context, and avoid silently ignoring failures.

</>
Copy
try {
    insert accountRecord;
} catch (DmlException exceptionItem) {
    System.debug(exceptionItem.getMessage());
    throw exceptionItem;
}

What is a savepoint in Apex?

A savepoint marks a position within the current transaction. If later logic fails, Database.rollback() can restore the database state to that savepoint. Savepoints and rollbacks consume transaction resources and should be used deliberately.

Apex testing interview questions and answers

Why are Apex tests required?

Apex tests verify expected behavior, protect against regressions, and are required for deploying Apex to production. Salesforce also requires an overall code-coverage threshold for deployment, but coverage alone does not demonstrate that the code is correct.

What should a good Apex test method verify?

  • Expected output and database changes.
  • Positive and negative behavior.
  • Bulk processing with multiple records.
  • Permission-sensitive or sharing-sensitive behavior where relevant.
  • Exception paths and partial failures.
  • Asynchronous processing and callouts through supported test techniques.
  • Boundary values and empty collections.

What are Test.startTest() and Test.stopTest() used for?

Test.startTest() creates a new governor-limit context for the portion of code under test. Test.stopTest() ends that context and causes queued asynchronous work to execute as supported by the testing framework. Assertions should then verify the resulting behavior.

What is @testSetup in Apex?

A method annotated with @testSetup creates common test data once for the test class. Each test method receives an isolated copy of that data, reducing duplication while preserving test independence.

How are HTTP callouts tested in Apex?

Tests use mock implementations such as HttpCalloutMock and register them with Test.setMock(). This prevents the test from depending on a live external endpoint and lets the developer simulate success, error, and malformed-response scenarios.

Scenario-based Salesforce Apex interview questions

How would you prevent duplicate records in Apex?

First determine whether Salesforce matching rules and duplicate rules can enforce the requirement declaratively. When Apex is required, normalize the matching fields, collect candidate keys for all incoming records, query existing records once, detect duplicates within both the database and the current transaction, and add clear errors to affected records in a before trigger.

How would you update parent records when child records change?

Collect parent IDs from new and old child records, run aggregate queries when suitable, calculate the new parent values in Maps, and perform one parent update outside all loops. The implementation must handle insert, update, delete, undelete, parent reassignment, and bulk operations.

How would you process millions of records?

Use Batch Apex or another platform-supported large-volume architecture. Select only required fields, use selective filters, choose a suitable batch scope, make processing restartable and idempotent, capture failures, and monitor jobs. For integration-driven workloads, also consider Bulk API and event-driven processing.

How would you call an external API after a record is saved?

Avoid making the callout directly from ordinary trigger logic. Collect the required record IDs and enqueue asynchronous processing that permits callouts, such as Queueable Apex implementing Database.AllowsCallouts. Use a Named Credential, handle timeouts and non-success responses, and design retry and logging behavior without creating duplicate external requests.

How would you design reusable Apex for several triggers and entry points?

Keep triggers and controllers thin, move business rules into service or domain classes, isolate queries in selector classes, isolate data changes where useful, pass collections rather than single records, and design methods that are independent of a specific user interface. Dependencies that call external services or perform complex operations can be injected or wrapped to improve testing.

Apex coding interview questions to practise

  1. Write a bulk-safe trigger that copies a field from Account to newly created Contacts.
  2. Write Apex that groups Contacts by Account ID without using nested queries inside loops.
  3. Create a Queueable class that sends record data to an external service.
  4. Write a Batch Apex class that updates records selected by a query locator.
  5. Create a test class for a trigger that handles insert, update, and bulk operations.
  6. Use Database.insert(records, false) and return individual error messages.
  7. Write a method that accepts a Set of record IDs and returns a Map keyed by ID.
  8. Prevent trigger recursion while allowing multiple valid record groups in one transaction.
  9. Enforce object and field permissions before exposing queried data.
  10. Refactor code containing SOQL and DML inside loops into a bulk-safe implementation.

Frequently asked Salesforce Apex interview questions

Which Apex topics should a fresher prepare for an interview?

A fresher should understand Apex syntax, classes, methods, collections, SOQL, SOSL, DML, triggers, governor limits, bulkification, exception handling, and test classes. The candidate should also be able to explain a simple trigger or service-class example.

What Apex questions are common for three years of Salesforce experience?

Interviews at this level commonly include trigger frameworks, bulk processing, asynchronous Apex, callouts, security enforcement, integration error handling, testing patterns, recursion control, and scenario-based debugging.

What Apex questions are common for five years of Salesforce experience?

Experienced candidates are often asked to justify architecture choices, handle large data volumes, design transaction boundaries, compare asynchronous tools, secure Apex services, diagnose governor-limit failures, create reusable frameworks, and explain deployment and production-support practices.

How should scenario-based Apex interview questions be answered?

Start by clarifying data volume, transaction source, security context, integration behavior, and failure requirements. Then explain the chosen design, governor-limit impact, bulk behavior, test strategy, error handling, and alternatives. Interviewers usually value reasoning more than a memorized code sample.

What is the best way to prepare for an Apex coding interview?

Practise writing bulk-safe code without SOQL or DML inside loops, use Sets and Maps confidently, write test methods with meaningful assertions, and review trigger, Queueable, Batch Apex, callout, and security scenarios. Be prepared to explain why the code works for one record and for hundreds of records.

Salesforce Apex interview content QA checklist

  • Confirm that every Apex example processes collections rather than assuming a single record.
  • Verify that no newly added example places SOQL or DML inside a loop.
  • Check that trigger answers distinguish before and after contexts correctly.
  • Confirm that sharing keywords are not presented as automatic CRUD and field-level security enforcement.
  • Verify that asynchronous Apex comparisons distinguish future, Queueable, Batch, and Scheduled Apex accurately.
  • Check that testing guidance includes assertions, bulk cases, negative cases, and asynchronous execution.
  • Confirm that callout guidance uses secure credential configuration and does not recommend hard-coded secrets.
  • Review governor-limit statements against current Salesforce documentation before publishing numeric limits.
  • Ensure scenario answers discuss data volume, failure handling, security, and transaction boundaries.
  • Verify that the FAQ section contains no more than five topic-specific Apex interview questions.