Salesforce Apex Interview Questions and Answers
Preparing for a Salesforce developer interview means covering a broad set of topics, from Apex fundamentals and SOQL to trigger design, governor limits, asynchronous processing, and test coverage. This guide covers 35 role-relevant Salesforce Apex interview questions and answers to help you prepare effectively, whether you are a fresher entering the Salesforce ecosystem or an experienced developer looking to sharpen your knowledge before an interview.
Apex Testing and Deployment Questions
1. Why are test classes important in Apex?
Test classes verify that your Apex code behaves correctly across expected and edge-case scenarios. Salesforce requires test coverage to protect org integrity before deploying code to production. Beyond the coverage requirement, well-written tests catch regressions when existing code is changed, document expected behavior, and validate that business logic holds under bulk data conditions. Test classes should test behavior, not just lines of code.
2. What is the minimum code coverage required for Apex deployment?
Salesforce requires at least 75% code coverage across all Apex classes and triggers in the org before a deployment to production can proceed. Individual classes do not each need 75%; it is the aggregate coverage across the org that must meet the threshold. However, best practice is to aim for 90% or higher and to write meaningful assertions rather than tests designed only to inflate the coverage number.
3. What is the purpose of Test.startTest() and Test.stopTest()?
Test.startTest() and Test.stopTest() create a new governor limit context within a test method. Code executed between these two calls gets a fresh set of governor limits, which prevents the setup and assertion portions of the test from consuming limits that count against the code under test. Test.stopTest() also forces any asynchronous operations queued inside the block, such as Future methods or Batch jobs, to execute synchronously so their results can be asserted in the same test method.
4. How do you create test data in Apex tests?
Test data should always be created within the test class itself using DML statements, since test methods run in an isolated context and do not have access to org data by default. For shared data needed across multiple test methods, use a @testSetup annotated method, which runs once before the test class executes and rolls back after all tests complete. Avoid using SeeAllData=true unless absolutely necessary, as it creates a dependency on real org data that can make tests brittle.
@testSetup
static void setupData() {
Account acc = new Account(Name = 'Test Account');
insert acc;
}
@isTest
static void testAccountUpdate() {
Account acc = [SELECT Id FROM Account LIMIT 1];
acc.Name = 'Updated Name';
update acc;
System.assertEquals('Updated Name', [SELECT Name FROM Account WHERE Id = :acc.Id].Name);
}
Apex Trigger Interview Questions
1. What is an Apex trigger in Salesforce?
An Apex trigger is code that executes automatically before or after specific database events on a Salesforce object, such as record inserts, updates, deletes, or undeletes. Triggers allow developers to perform custom logic that cannot be handled declaratively, such as updating related records, enforcing complex validation, or calling external systems. Each trigger is associated with a specific sObject and one or more events.
Learn via our Video Courses
2. What is the difference between before trigger and after trigger?
| Feature | Before Trigger | After Trigger |
|---|---|---|
| Timing | Fires before record is saved to database | Fires after record is saved to database |
| Record ID available | No (record not yet committed) | Yes |
| Can modify triggering record | Yes, directly via Trigger.new
|
No (requires additional DML, not recommended) |
| Use case | Validation, field updates on the same record | Creating or updating related records |
3. What are trigger context variables such as Trigger.new, Trigger.old, Trigger.newMap, and Trigger.oldMap?
Trigger.new is a list of the new versions of the records being processed, available in insert, update, and undelete triggers. Trigger.old is a list of the old versions of the records, available in update and delete triggers. Trigger.newMap is a map of record IDs to the new record versions, and Trigger.oldMap is a map of record IDs to the old versions. The map variants are particularly useful in bulkified triggers for fast lookups of specific records by ID.
4. What is the Salesforce order of execution?
When a record is saved in Salesforce, the platform processes events in a defined sequence: system validation, before triggers, custom validation rules, duplicate rules, after triggers, assignment rules, auto-response rules, workflow rules, processes and flows, escalation rules, and then the final commit to the database followed by post-commit logic such as sending emails and making callouts. Understanding this order is important for debugging unexpected behavior and ensuring custom logic fires at the right time.
5. How do you prevent recursive triggers in Salesforce?
Recursion occurs when a trigger causes a DML operation that fires the same trigger again, leading to repeated execution and potential governor limit errors. The standard approach is to use a static Boolean variable in a helper class that is set to true the first time the trigger fires. The trigger checks this flag before executing its logic and exits early on subsequent invocations within the same transaction.
public class TriggerHelper {
public static Boolean isFirstRun = true;
}
// In trigger
if (TriggerHelper.isFirstRun) {
TriggerHelper.isFirstRun = false;
// trigger logic here
}
6. What is trigger bulkification, and why is it important?
Bulkification means writing trigger logic that handles a collection of records efficiently rather than processing one record at a time. Salesforce can process up to 200 records in a single trigger invocation, such as when records are imported via Data Loader. A non-bulkified trigger that runs a SOQL query or DML statement per record will exceed governor limits at that scale. Bulkified triggers collect all record IDs first, perform a single SOQL query outside any loop, process results using Maps, and perform a single DML call on the full collection at the end.
Asynchronous Apex Interview Questions
1. What is asynchronous Apex?
Asynchronous Apex refers to Apex code that executes outside the context of the user's current transaction, in a separate thread or job queue. It is used for operations that are too long or resource-intensive for synchronous execution, such as making HTTP callouts, processing large data volumes in batches, or chaining multiple sequential operations. Asynchronous Apex has higher governor limits than synchronous Apex in most categories.
2. What is the difference between Future methods, Queueable Apex, Batch Apex, and Scheduled Apex?
| Feature | Future Method | Queueable Apex | Batch Apex | Scheduled Apex |
|---|---|---|---|---|
| Chaining jobs | No | Yes | No | No |
| Returns job ID | No | Yes | Yes | Yes |
| Callouts allowed | Yes (with annotation) | Yes | Yes (start/execute) | No (directly) |
| State between jobs | No | Yes (via member vars) | Via Database.Stateful
|
No |
| Batch size control | No | No | Yes | No |
| Best for | Simple async/callout | Chained jobs, complex async | Large data processing | Scheduled recurring logic |
3. When would you use Batch Apex?
Batch Apex is used when you need to process a large number of records that exceeds synchronous governor limits, such as updating millions of records, performing data migration, or running nightly data cleanup jobs. The Batch Apex framework divides the total record set into configurable chunks (default 200 records per batch), processes each chunk in a separate transaction, and calls a finish method when all chunks are done. It is ideal for operations that can tolerate eventual completion rather than immediate results.
4. When would you use Queueable Apex instead of Future methods?
Use Queueable Apex when you need to chain jobs sequentially, when you want a job ID to monitor execution status, when you need to pass complex objects (not just primitives and collections of IDs) between async contexts, or when your async logic has multiple steps that depend on each other. Future methods are simpler but do not support chaining, do not return job IDs, and only accept primitive parameters. Queueable Apex is generally preferred for anything beyond a simple fire-and-forget callout.
5. How do you make callouts from Apex?
Apex callouts use the HttpRequest and HttpResponse classes. You set the endpoint, method, headers, and body on the request object, then call Http.send() to execute it. Callouts must be made from asynchronous context (Future method, Queueable, or Batch) if they are triggered from a trigger, since synchronous transactions with DML cannot also make callouts. The endpoint must be registered in Remote Site Settings or a Named Credential.
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/data');
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer ' + token);
Http http = new Http();
HttpResponse res = http.send(req);
String body = res.getBody();
Frequently Asked Questions About Salesforce Apex Interviews
1. What are the most important Salesforce Apex interview topics?
The most frequently tested topics are Apex triggers and context variables, governor limits and bulkification, SOQL best practices, the difference between synchronous and asynchronous Apex, test class structure and coverage requirements, and scenario-based questions on trigger recursion, batch debugging, and security with sharing rules.
2. How should freshers prepare for Salesforce Apex interviews?
Start with the Apex basics: classes, sObjects, collections, SOQL, and DML. Then move into triggers and governor limits, as these appear in almost every interview regardless of experience level. Build small projects on a free Salesforce Developer Edition org to practice writing and testing real Apex code. The Salesforce tutorial on Scaler and the official Salesforce Apex Developer Guide are the two most important reading resources.
3. What is the difference between Apex and Java?
Apex is syntactically similar to Java but runs only on the Salesforce platform, has built-in SOQL and DML support, enforces governor limits per transaction, and does not support multi-threading. Java is a general-purpose language with no such platform constraints. Developers with a Java background typically find Apex approachable but need to learn the Salesforce data model and governor limit patterns specifically.
4. Are Apex triggers asked in Salesforce developer interviews?
Yes, trigger questions are among the most consistently asked topics across all interview levels. Expect questions on before vs after triggers, context variables, bulkification, recursion prevention, and the Salesforce order of execution. Senior-level interviews often include trigger framework design questions.
5. What are the most common Apex scenario-based interview questions?
The most common scenarios involve diagnosing and fixing recursive triggers, handling partial batch failures, designing a reusable service class, explaining the impact of sharing rules on data visibility, and building an external REST API integration. These questions test whether you can apply theoretical knowledge to realistic production problems.
6. How much code coverage is required for Apex deployment?
The platform requires a minimum of 75% aggregate code coverage across all Apex classes and triggers before deployment to production. Best practice is to target 90% or above and to write tests that assert correct behavior, not just tests that execute lines of code without verifying outcomes.
Governor Limits and Bulkification Questions
1. What are best practices for using Maps in bulkified triggers?
Build the Map before any loop using a single SOQL query keyed by record ID. Use Map<Id, SObject> with a SOQL query wrapped in the Map constructor for concise syntax. When you need to look up related records by a field other than ID, build a secondary Map keyed by that field. Always use Map.get() with a null check or Map.containsKey() before accessing values to prevent null pointer exceptions.
Map accountMap = new Map(
[SELECT Id, Name, Industry FROM Account WHERE Id IN :accountIds]
);
2. What are governor limits in Salesforce?
Governor limits are runtime limits enforced by the Salesforce platform to ensure that no single tenant's code consumes an excessive share of shared server resources. They apply per transaction and cover areas such as SOQL queries (100 per transaction), DML statements (150 per transaction), heap size (6 MB for synchronous, 12 MB for asynchronous), CPU time (10 seconds for synchronous), and callout limits. Exceeding any governor limit throws a fatal runtime exception that rolls back the transaction.
3. Why does Salesforce enforce governor limits?
Salesforce is a multi-tenant platform where many organizations share the same underlying infrastructure. Governor limits prevent poorly written or malicious code from monopolizing resources and degrading performance for other tenants. They also serve as a design forcing function, encouraging developers to write efficient, bulk-safe code rather than relying on brute-force approaches that would fail at scale.
4. How do you write bulk-safe Apex code?
Bulk-safe Apex collects all processing inputs before any loop, performs SOQL queries and DML operations once on full collections, uses Maps for O(1) lookups instead of nested loops or repeated queries, and avoids callouts inside loops. The pattern is: collect IDs from the trigger context, query all needed records in one statement, build a Map for fast access, process the collection in a loop using only Map lookups, then perform a single DML call on the results list.
5. How do you handle the "too many SOQL queries: 101" error?
This error means a transaction exceeded 100 SOQL queries. The fix is to identify queries inside loops using debug logs or Apex replay debugger, move them outside the loop, and use Maps to provide in-memory lookup. If the issue is in a trigger invoked by a large data load, also check whether related triggers, workflows, or process builders are each contributing queries. Combining logic into a single trigger handler class reduces the risk of multiple independent queries accumulating across different automation layers.
Salesforce Apex Basics Interview Questions
1. How is Apex different from Java?
Apex shares a syntax similar to Java but has several important differences. Apex runs exclusively on the Salesforce platform and cannot be used outside of it, whereas Java is a general-purpose language. Apex has built-in support for Salesforce objects, SOQL queries inline in code, and DML operations. It enforces governor limits to prevent any single tenant from monopolizing shared server resources, a constraint Java does not have. Apex also does not support multi-threading and has a more limited standard library. For Java fundamentals that apply to Apex, the Java interview questions on InterviewBit and the Java tutorial on Scaler are helpful references.
2. What are Apex classes and methods?
An Apex class is a template or blueprint that defines the data and behavior for objects in Apex, similar to a class in Java. Classes can contain member variables, methods, constructors, and inner classes. Methods are functions defined inside a class that perform specific actions or return values. Classes can be marked with access modifiers like public, private, or global, and can implement interfaces or extend other classes.
public class AccountService {
public static void updateAccountName(Id accountId, String newName) {
Account acc = [SELECT Id FROM Account WHERE Id = :accountId LIMIT 1];
acc.Name = newName;
update acc;
}
}
3. What are sObjects in Apex?
An sObject is any object that can be stored in the Salesforce database. The term stands for Salesforce object. Every standard Salesforce object like Account, Contact, and Opportunity, and every custom object created in an org, is an sObject. In Apex, sObjects are used as typed variables to hold record data, and they map directly to database rows. You can query them with SOQL and manipulate them with DML statements.
4. What are collections in Apex, and when do you use List, Set, and Map?
Apex supports three collection types. A List is an ordered collection that allows duplicate values, used when order matters or when you need index-based access. A Set is an unordered collection that does not allow duplicates, useful for storing unique IDs or values you need to check membership against. A Map stores key-value pairs and provides fast lookup by key, commonly used in bulkified trigger logic to map record IDs to their corresponding records or related data.
5. What is Apex in Salesforce, and why is it used?
Apex is a strongly typed, object-oriented programming language that runs on the Salesforce platform. It is used to implement custom business logic that cannot be achieved through declarative tools like Flow or Process Builder alone. Common use cases include writing triggers that respond to database events, building reusable service classes, making HTTP callouts to external systems, and implementing complex data transformations. Apex is compiled, stored, and executed entirely on Salesforce servers.
Scenario-Based and Experienced Apex Interview Questions
1. A batch job fails for only a few records. How would you debug and handle partial failures?
Batch Apex processes records in chunks. If one chunk fails, the others continue by default unless the batch is configured to stop on first error. To debug, check the Apex Jobs page in Setup for the error message associated with the failed batch. Enable debug logs for the batch user to capture detailed information. In the batch's execute method, wrap the processing logic in a try-catch block to capture and log individual record failures without failing the entire batch. Use Database.update(records, false) instead of update records to allow partial DML success and collect the Database.SaveResult list to identify which specific records failed and why.
2. A trigger is updating the same object and causing recursion. How would you fix it?
The root cause is that the trigger's DML operation fires the same trigger again. The fix involves introducing a static Boolean flag in a separate helper class. On the first execution, the flag is true and the trigger logic runs, immediately setting the flag to false. Any re-entry into the trigger within the same transaction sees the flag as false and exits early. A more robust pattern used in trigger frameworks is a static Set that tracks which sObject and event combinations have already been processed, allowing more granular control than a single Boolean.
3. How would you design an Apex service class for reusable business logic?
A service class encapsulates business logic in a single location so it can be called from triggers, controllers, batch jobs, and other contexts without duplication. Design principles include: making the class public with static methods so it can be called without instantiation, accepting collections of sObjects as parameters rather than single records to ensure bulk safety, keeping the class free of UI or trigger-specific dependencies so it is reusable, and separating query logic from processing logic. This aligns with the single responsibility principle and makes the code testable in isolation.
4. How do with sharing, without sharing, and inherited sharing affect Apex execution?
| Keyword | Behavior |
|---|---|
with sharing |
Enforces the running user's sharing rules; records the user cannot see are excluded from queries |
without sharing |
Ignores sharing rules; all records are accessible regardless of user permissions |
inherited sharing |
Inherits the sharing context of the calling class; defaults to without sharing if called from a context with no sharing declaration |
By default, Apex classes run without sharing unless explicitly declared otherwise. Best practice is to use with sharing on all classes that handle user-facing queries to prevent unintended data exposure, and to use without sharing only in specific administrative or system-level contexts where full record access is deliberately required.
5. How would you integrate Salesforce with an external REST API using Apex?
The integration involves three components: a Named Credential or Remote Site Settings entry to whitelist the endpoint, an Apex HTTP callout class that builds and sends the request and parses the response, and an asynchronous mechanism (Queueable or Future method) to handle the callout if it is triggered from a DML context. For the response, parse the JSON body using JSON.deserialize into a typed Apex class or use JSON.deserializeUntyped for dynamic structures. Always handle HTTP error codes explicitly and log failures for observability. If two-way sync is needed, also configure a Connected App and incoming endpoint to receive callbacks from the external system.
SOQL, SOSL, and DML Interview Questions
1. What is SOQL, and how is it different from SQL?
SOQL stands for Salesforce Object Query Language. It is used to retrieve records from the Salesforce database. While it shares syntax similarities with SQL, SOQL is read-only and cannot perform joins across unrelated objects. It queries Salesforce objects and their fields, supports relationship traversal through parent-to-child and child-to-parent syntax, and can be written inline in Apex code. It does not support INSERT, UPDATE, or DELETE operations, which are handled by DML statements instead.
| Feature | SOQL | SQL |
|---|---|---|
| Purpose | Query Salesforce records | Query relational databases |
| DML support | No (use Apex DML separately) | Yes (INSERT, UPDATE, DELETE) |
| Joins | Relationship queries only | Full JOIN syntax |
| Inline in code | Yes, in Apex | No |
| Aggregate functions | Limited (COUNT, SUM, AVG, etc.) | Full support |
2. What is SOSL, and when would you use it instead of SOQL?
SOSL stands for Salesforce Object Search Language. It performs a text search across multiple objects and fields simultaneously, similar to a full-text search engine. You would use SOSL when you need to search for a keyword across several objects at once, such as finding all records mentioning a company name across Account, Contact, and Lead. SOQL is better when you know which object and fields to query and need precise filtering. SOSL is not suited for large volume record processing or complex relational queries.
3. What are DML operations in Apex?
DML stands for Data Manipulation Language. In Apex, DML operations are used to insert, update, delete, undelete, or upsert records in the Salesforce database. The main DML statements are insert, update, delete, upsert, undelete, and merge. Each DML statement counts against the governor limit of 150 DML operations per transaction, so they should always be used outside of loops and on collections of records rather than individual records.
4. How do you avoid SOQL queries inside loops?
Placing a SOQL query inside a loop will consume one query per iteration, which quickly hits the governor limit of 100 SOQL queries per transaction. The correct approach is to collect all the IDs or criteria needed before the loop, execute a single SOQL query outside the loop to retrieve all relevant records, store the results in a Map keyed by record ID, and then reference the Map inside the loop for fast lookups without additional queries.
Map accountMap = new Map(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
for (Contact con : contacts) {
Account acc = accountMap.get(con.AccountId);
}
5. What is a relationship query in SOQL? Explain parent-to-child and child-to-parent queries.
A parent-to-child relationship query retrieves a parent record along with its related child records in a subquery. For example, querying all Accounts and their related Contacts in a single query. A child-to-parent query traverses the relationship in the other direction, retrieving a child record and fields from its parent object using dot notation. Both types avoid the need for separate queries and reduce governor limit consumption.
// Child-to-parent
List contacts = [SELECT Id, Name, Account.Name FROM Contact];
// Parent-to-child
List accounts = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account];