Salesforce Platform Developer I Apex and Visualforce Interview Questions & Answers

Practice the most frequently asked Salesforce Platform Developer I Apex and Visualforce Interview Questions and Answers with detailed explanations, code examples, interview tips and real-world scenarios for Freshers and Experienced Developers.

100 Questions All Difficulty Levels Updated Dec 2026
1

What is Apex and what are its main characteristics? Easy

Apex is Salesforce's strongly typed, object-oriented programming language with Java-like syntax that runs on the Lightning Platform servers. It is used to write business logic, triggers, web services and batch jobs. Characteristics: runs in a multi-tenant environment under governor limits, tightly integrated with the database (inline SOQL and DML), case-insensitive, compiled and executed on the server, supports unit testing, and is deployed through metadata (with a minimum of 75 percent test coverage in production). Example: public class Greeter { public static String hello(String name) { return 'Hello ' + name; } }
apex basics
2

What are the primitive data types in Apex? Easy

Integer, Long, Double, Decimal, String, Boolean, Date, Datetime, Time, Id, Blob, Object. Also collections: List, Set, Map; sObjects (Account, custom__c); and enums. Notes: Decimal is used for currency; Id is 15 or 18 characters; Boolean defaults to null (not false) when uninitialised; Strings are immutable and compared with equals or == (case-insensitive).
apex datatypes
3

What are Lists, Sets and Maps in Apex? Easy

- List: ordered collection allowing duplicates, index access. List accs = new List(); - Set: unordered unique elements, fast contains. Set ids = new Set(); - Map: key-value pairs with unique keys. Map accMap = new Map([SELECT Id, Name FROM Account]); Use sets of IDs for filtering queries, and maps for quick lookup of related records (bulk-safe patterns).
apex collections
4

What is an sObject? Easy

An sObject is a Salesforce object record in Apex (standard such as Account or custom such as Invoice__c). You create it with the new keyword and set fields: Account a = new Account(Name = 'Acme'); a.Industry = 'Technology'; insert a; Generic sObject variables (sObject s = a;) allow dynamic code, and fields can be accessed with s.get('Name').
apex sobject
5

What is SOQL and what is its syntax? Easy

SOQL (Salesforce Object Query Language) retrieves records from the database. Syntax: SELECT fields FROM object WHERE conditions ORDER BY field LIMIT n. Example: List cs = [SELECT Id, LastName, Account.Name FROM Contact WHERE Email != null ORDER BY LastName LIMIT 10]; Features: relationship queries (parent via dot, child via subquery), aggregate functions (COUNT, SUM), GROUP BY, bind variables (:variable) and FOR UPDATE.
apex soql
6

What is SOSL and how does it differ from SOQL? Easy

SOSL (Salesforce Object Search Language) searches text across multiple objects and fields at once, returning lists of sObjects. Example: List> res = [FIND 'Acme*' IN ALL FIELDS RETURNING Account(Name), Contact(LastName)]; SOQL queries one object (with relationships) with exact filters; SOSL is for text search across objects and is faster for keyword search.
apex sosl
7

What DML operations does Apex support? Easy

insert, update, upsert, delete, undelete and merge, plus Database class methods (Database.insert(list, allOrNone)) that return Save results. DML limits: 150 statements per transaction and 10,000 records per transaction. Example: List accs = new List{new Account(Name='A'), new Account(Name='B')}; insert accs;
apex dml
8

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

The DML statement insert is all-or-nothing: if any record fails, an exception is thrown and the whole operation rolls back. Database.insert(records, false) allows partial success: it returns an array of SaveResult objects so you can check each record for errors with isSuccess() and getErrors(), and successful records are committed.
apex database-class
9

What is an Apex trigger and when does it execute? Easy

A trigger is Apex code that runs before or after DML events on an object: before insert/update/delete and after insert/update/delete/undelete. Syntax: trigger AccountTrigger on Account (before insert, before update) { for (Account a : Trigger.new) { a.Description = 'Checked'; } } Use before triggers to validate or update the same record, and after triggers to access record IDs or modify related records.
apex triggers
10

What are the trigger context variables? Easy

Trigger.new (list of new records), Trigger.old (previous values), Trigger.newMap and Trigger.oldMap (Id to record maps), Trigger.isInsert, isUpdate, isDelete, isUndelete, Trigger.isBefore, isAfter, Trigger.isExecuting and Trigger.size, Trigger.operationType (enum). Trigger.new is read-write in before triggers and read-only in after triggers; Trigger.old is not available for insert and Trigger.new is not available for delete.
apex trigger-context
11

What are trigger best practices? Easy

- One trigger per object and delegate logic to handler classes. - Bulkify: handle up to 200 records, no SOQL or DML inside loops. - Use collections (Sets and Maps) for queries and updates. - Avoid hard-coded IDs; use custom metadata or queries. - Prevent recursion with static variables. - Add tests with bulk data, and keep triggers logic-less. Example trigger delegates: trigger OpportunityTrigger on Opportunity (before insert, after update) { OpportunityTriggerHandler.run(); }
apex trigger-best-practices
12

What are the common governor limits in Apex? Easy

Per synchronous transaction: 100 SOQL queries, 150 DML statements, 50,000 records returned by SOQL, 10,000 DML rows, 10 seconds CPU time (asynchronous 60 seconds), 6 MB heap (12 MB async), 100 callouts, 10 future calls per transaction, 5 queueable jobs chained per transaction (can add 1 in async). Limits protect the multi-tenant platform and are checked with the Limits class (Limits.getQueries()).
apex governor-limits
13

How do you handle exceptions in Apex? Easy

Use try, catch and finally blocks: try { insert acc; } catch (DmlException e) { System.debug(e.getMessage()); } finally { /* cleanup */ } Common types: DmlException, QueryException, NullPointerException, ListException, CalloutException, LimitException (cannot be caught). Create custom exceptions by extending Exception: public class MyException extends Exception {} Use addError() on records in triggers to show validation messages to users.
apex exception-handling
14

How do you define a class, methods and access modifiers in Apex? Easy

public class Calculator { private Integer total = 0; public Integer add(Integer a, Integer b) { return a + b; } public static Integer square(Integer n) { return n * n; } } Access modifiers: private (default for members), protected, public (within the namespace/org), global (accessible outside the namespace, used in managed packages). Classes can be abstract, virtual, with sharing / without sharing / inherited sharing.
apex classes
15

What do "with sharing", "without sharing" and "inherited sharing" mean? Easy

- with sharing: the class enforces the current user's record-level sharing rules. - without sharing: runs in system context ignoring sharing (use carefully). - inherited sharing: inherits sharing from the calling class (default for entry points is with sharing). Note: sharing does not enforce object or field permissions; use WITH USER_MODE, WITH SECURITY_ENFORCED or stripInaccessible for CRUD/FLS.
apex sharing
16

What is the difference between static and instance variables and methods? Easy

Static members belong to the class and are shared (initialised once per transaction); they are accessed with ClassName.method(). Instance members belong to an object created with new, each with its own state. Static variables are commonly used for trigger recursion control and constants.
apex static
17

What are constructors and how do you use them? Easy

A constructor is a special method with the class name and no return type, used to initialise objects. public class Person { public String name; public Person(String n) { name = n; } public Person() { this('Unknown'); } } Apex provides a default no-argument constructor if none is defined. Visualforce controller constructors also initialise page state.
apex constructors
18

What is an interface in Apex? Easy

An interface defines method signatures that implementing classes must provide. public interface Shape { Decimal area(); } public class Circle implements Shape { public Decimal area() { return 3.14 * r * r; } } Interfaces support polymorphism and are used by platform features such as Schedulable, Database.Batchable and Comparable.
apex interfaces
19

Why are unit tests required in Apex and what is the minimum coverage? Easy

Salesforce requires at least 75 percent overall Apex code coverage to deploy to production, with all tests passing, and every trigger must have some coverage. Tests ensure correct behaviour and protect against regressions. Use @isTest classes, test data created in the test (no seeAllData), and assertions with System.assertEquals or Assert class methods.
apex test
20

What annotations are used in Apex tests? Easy

@isTest marks test classes and methods; @testSetup creates shared test data once; @TestVisible exposes private members to tests; testMethod keyword (legacy); System.runAs(user) runs code as a given user; Test.startTest() and Test.stopTest() reset governor limits and run async code synchronously; @isTest(SeeAllData=true) is discouraged.
apex test annotations
21

What is a @future method? Easy

An asynchronous method that runs in a separate thread when resources are available, used for callouts from triggers or mixed DML separation. Rules: static, return void, parameters must be primitives or collections of primitives (no sObjects), and @future(callout=true) permits HTTP callouts. Limits: 50 future calls per transaction (asynchronous limit), and cannot be called from batch or future methods. Prefer Queueable Apex for most new work.
apex future
22

What is Queueable Apex? Easy

A class implementing Queueable with an execute(QueueableContext) method, enqueued with System.enqueueJob(new MyJob()). Advantages over future: accepts complex types (sObjects), returns a job ID for monitoring, supports chaining jobs, and finalizers. Example: public class MyJob implements Queueable { public void execute(QueueableContext ctx) { /* work */ } }
apex queueable
23

What is Batch Apex and when is it used? Easy

Batch Apex processes large data volumes (millions of records) in chunks (default 200, up to 2,000) asynchronously. Implement Database.Batchable with start() (returns QueryLocator or Iterable), execute() (process a batch) and finish() (post-processing). Run with Database.executeBatch(new MyBatch(), 200). Each batch has its own governor limits. Used for data clean-up, mass updates and recalculations.
apex batch
24

How do you schedule Apex? Easy

Implement Schedulable with execute(SchedulableContext) and schedule via the UI (Setup > Apex Classes > Schedule Apex) or code with a CRON expression: System.schedule('Nightly', '0 0 2 * * ?', new MyScheduler()); The cron format: seconds minutes hours day-of-month month day-of-week year (optional). Limit of 100 scheduled jobs.
apex schedulable
25

What is Visualforce? Easy

A framework for building custom user interfaces with a tag-based markup language (like HTML with components) and an Apex controller. Pages are created in Setup or the Developer Console and accessed by URL (/apex/PageName). Visualforce supports standard controllers, custom controllers and controller extensions, and is still used for PDF generation and legacy UIs, while Lightning Web Components are preferred for new development.
visualforce basics
26

What are the types of controllers in Visualforce? Easy

- Standard controller: built-in logic for an object (standardController="Account"), provides save, edit, delete, cancel and access to the record. - Custom controller: an Apex class providing all logic (controller="MyController"). - Controller extension: an Apex class that adds or overrides logic of a standard or custom controller (extensions="MyExt"), with a constructor taking ApexPages.StandardController. - Standard list controller for lists with pagination.
visualforce controllers
27

What are common Visualforce components? Easy

apex:page, apex:form, apex:inputField, apex:outputField, apex:inputText, apex:commandButton, apex:commandLink, apex:pageBlock, apex:pageBlockSection, apex:pageBlockTable, apex:repeat, apex:outputPanel, apex:actionFunction, apex:actionSupport, apex:pageMessages, apex:detail, apex:relatedList, and apex:includeLightning.
visualforce tags
28

How do you use expression syntax and merge fields in Visualforce? Easy

Expressions use {! } to bind values and controller members: {!account.Name}, {!$User.FirstName}, {!IF(x > 5, 'Big', 'Small')}. Global variables: $User, $Profile, $Page, $Resource, $Label, $Action, $Setup. Getter and setter methods or properties in the controller are accessed by name (public String name {get; set;}).
visualforce expressions
29

What are Lightning Web Components (LWC) and how do they relate to Apex? Easy

LWC is a modern web-standards-based framework (HTML, JavaScript, CSS) for building Lightning UI. LWCs call Apex through @AuraEnabled methods (cacheable=true for read-only) imported in the component, or use Lightning Data Service (lightning-record-form, wire adapters) for CRUD without Apex. Example Apex: @AuraEnabled(cacheable=true) public static List getAccounts() { return [SELECT Id, Name FROM Account LIMIT 10]; }
apex lightning lwc
30

How do you enforce CRUD and field-level security in Apex? Easy

Apex runs in system mode by default, so enforce explicitly: WITH USER_MODE in SOQL (WITH USER_MODE) or Database.query with AccessLevel.USER_MODE, WITH SECURITY_ENFORCED (throws on inaccessible fields), Security.stripInaccessible(AccessType.READABLE, records) to remove inaccessible fields, and schema checks like Schema.sObjectType.Account.isCreateable(). Always apply to code exposed to users such as @AuraEnabled methods.
apex security crud-fls
31

How do you debug Apex? Easy

Use System.debug() statements with log levels, the Developer Console (Debug Logs, Execution Log, Query Editor, Execute Anonymous), Debug Logs in Setup with trace flags per user, the Apex Replay Debugger in VS Code and Checkpoints. Check governor usage in the Limits section of logs.
apex debug
32

How do you store configuration for Apex without hard-coding? Easy

Use Custom Metadata Types (deployable, query with SOQL, no DML limits in some contexts, cached), Custom Settings (list/hierarchy, accessible via getInstance()), Custom Labels for text and Named Credentials for endpoints. Avoid hard-coded Ids, URLs and thresholds.
apex custom-settings
33

What is dynamic Apex and dynamic SOQL? Easy

Dynamic Apex uses describe methods and generic types at runtime: Schema.getGlobalDescribe(), Schema.SObjectType.Account.fields.getMap(), and sObject.get/put. Dynamic SOQL builds query strings executed with Database.query(queryString). Use String.escapeSingleQuotes() or bind variables (Database.queryWithBinds) to prevent SOQL injection.
apex dynamic-apex
34

How do you make an HTTP callout in Apex? Easy

Use HttpRequest, Http and HttpResponse: HttpRequest req = new HttpRequest(); req.setEndpoint('callout:My_Named_Credential/api/items'); req.setMethod('GET'); HttpResponse res = new Http().send(req); if (res.getStatusCode() == 200) { Map data = (Map) JSON.deserializeUntyped(res.getBody()); } Use Named Credentials for endpoints/authentication; remote sites must be authorised; tests need HttpCalloutMock.
apex callouts
35

How do you work with JSON in Apex? Easy

JSON.serialize(obj) converts objects to JSON; JSON.deserialize(jsonString, Type.class) converts JSON to typed objects; JSON.deserializeUntyped returns Maps and Lists. JSONGenerator and JSONParser provide streaming. Wrapper classes with matching property names make deserialisation easy.
apex json
36

What is bulkification and how do you write a bulk-safe trigger? Medium

Bulkification means code handles many records (up to 200 per trigger invocation) in one transaction without exceeding governor limits. Rules: no SOQL or DML inside for-loops, use collections. Bad: for (Contact c : Trigger.new) { Account a = [SELECT Id FROM Account WHERE Id = :c.AccountId]; update a; } Good: Set accIds = new Set(); for (Contact c : Trigger.new) { if (c.AccountId != null) accIds.add(c.AccountId); } Map accs = new Map([SELECT Id, Description FROM Account WHERE Id IN :accIds]); for (Account a : accs.values()) { a.Description = 'Updated'; } update accs.values();
apex bulkification
37

Show the trigger handler pattern. Medium

Trigger (logic-less): trigger OpportunityTrigger on Opportunity (before insert, before update, after update) { OpportunityTriggerHandler.handle(Trigger.operationType, Trigger.new, Trigger.oldMap); } Handler: public class OpportunityTriggerHandler { public static void handle(System.TriggerOperation op, List newList, Map oldMap) { switch on op { when BEFORE_INSERT, BEFORE_UPDATE { setDefaults(newList); } when AFTER_UPDATE { createFollowUps(newList, oldMap); } } } private static void setDefaults(List opps) { /* ... */ } private static void createFollowUps(List opps, Map oldMap) { /* ... */ } } Benefits: testability, readability, reuse and control of execution order.
apex trigger handler
38

How do you prevent trigger recursion? Medium

Recursion happens when an after-update trigger updates records of the same object, firing the trigger again. Use a static Boolean or a static Set to track processed records: public class TriggerControl { public static Set processed = new Set(); } In the handler: for each record if (!TriggerControl.processed.contains(r.Id)) { process; add to set }. Using a Boolean flag blocks all later records in the same transaction, which may skip legitimate records in a bulk operation, so a set of IDs is safer. Also compare old and new values to run only when relevant fields change.
apex recursion
39

Explain the order of execution for a DML operation. Medium

1. Load original record (for updates) and run system validation. 2. Before-save flows. 3. Before triggers. 4. System validation again and custom validation rules. 5. Duplicate rules. 6. Save the record to the database (not committed). 7. After triggers. 8. Assignment rules, auto-response rules, workflow rules (with field updates that may re-fire before/after triggers once). 9. After-save flows and processes. 10. Escalation rules, entitlement rules. 11. Roll-up summary and cross-object workflow updates; sharing recalculation. 12. Commit; then post-commit logic (email, async jobs). Developers need it to understand why values change and which logic runs first.
apex order-of-execution
40

Show SOQL examples for parent-to-child and child-to-parent queries. Medium

Child-to-parent (dot notation, up to 5 levels): SELECT Id, LastName, Account.Name, Account.Owner.Name FROM Contact Parent-to-child (subquery with child relationship name): SELECT Id, Name, (SELECT Id, LastName FROM Contacts), (SELECT Id, Amount FROM Opportunities WHERE StageName = 'Closed Won') FROM Account Custom relationships use __r: SELECT Id, Project__r.Name FROM Task__c. Child relationship names are plural (Contacts) or custom names ending with __r.
apex soql relationships
41

How do you use aggregate functions, GROUP BY and HAVING in SOQL? Medium

Example: total opportunity amount per stage with at least 5 records: List res = [SELECT StageName, COUNT(Id) cnt, SUM(Amount) total FROM Opportunity GROUP BY StageName HAVING COUNT(Id) > 5]; for (AggregateResult ar : res) { String stage = (String) ar.get('StageName'); Decimal total = (Decimal) ar.get('total'); } Supported functions: COUNT, COUNT_DISTINCT, SUM, AVG, MIN, MAX. Aggregate queries count toward the 50,000 row limit differently and cannot use LIMIT with more than 2,000 groups in some contexts.
apex soql aggregate
42

What are FOR UPDATE, FOR VIEW, FOR REFERENCE and ALL ROWS in SOQL? Medium

- FOR UPDATE locks selected records to prevent other transactions from updating them until the transaction ends (avoids race conditions, can cause lock errors). - FOR VIEW and FOR REFERENCE update the "Last Viewed Date" and "Last Referenced Date" used for Recent Items. - ALL ROWS includes deleted and archived records (isDeleted = true) in the query. Example: [SELECT Id FROM Account WHERE Id = :accId FOR UPDATE];
apex soql for-update
43

How do you protect Apex from SOQL injection? Medium

Use static SOQL with bind variables ([SELECT Id FROM Account WHERE Name = :name]) which are automatically safe. For dynamic SOQL, use String.escapeSingleQuotes(), validate inputs against allow-lists (field names or sort order values), use Database.queryWithBinds, and apply WITH USER_MODE. Never concatenate raw user input directly into the query string.
apex soql injection
44

Compare Future, Queueable, Batch and Scheduled Apex. Medium

- Future: simple, primitive parameters, no job ID, no chaining; for quick async tasks or callouts. - Queueable: complex parameters, job ID, chaining, better monitoring; replaces most future uses. - Batch: large data volumes in chunks with own limits per batch, state via Stateful; for millions of records. - Scheduled: runs at specific times and can start batch or queueable jobs. Limits: 5 concurrent batch jobs running (100 in flex queue), 50 queueable jobs per transaction, 50 future calls per transaction. Choose by data volume, parameter needs, and scheduling.
apex async compare
45

Write a Batch Apex class that updates account descriptions and tracks the number of processed records. Medium

public class AccountBatch implements Database.Batchable, Database.Stateful { public Integer processed = 0; public Database.QueryLocator start(Database.BatchableContext bc) { return Database.getQueryLocator('SELECT Id, Description FROM Account WHERE Description = null'); } public void execute(Database.BatchableContext bc, List scope) { for (Account a : scope) { a.Description = 'Reviewed'; } update scope; processed += scope.size(); } public void finish(Database.BatchableContext bc) { System.debug('Processed: ' + processed); } } Run: Database.executeBatch(new AccountBatch(), 200); Database.Stateful keeps instance variables between batches (otherwise they reset for every execute).
apex batch stateful
46

How do you chain Queueable jobs and what are the limits? Medium

Inside execute() call System.enqueueJob(new NextJob()) to start another job after finishing. In synchronous contexts you can enqueue up to 50 jobs per transaction, but in an asynchronous (queueable) context only 1 child job per execution. Chains are limited by depth in Developer Edition/trial (5 levels) but unlimited in production. Use transaction finalizers (System.attachFinalizer) to handle failures and implement retries.
apex queueable chaining
47

How do you test HTTP callouts in Apex? Medium

Callouts are not allowed in tests, so implement HttpCalloutMock: public class MockResp implements HttpCalloutMock { public HTTPResponse respond(HTTPRequest req) { HttpResponse res = new HttpResponse(); res.setStatusCode(200); res.setBody('{"id":1}'); return res; } } In test: Test.setMock(HttpCalloutMock.class, new MockResp()); Test.startTest(); MyService.call(); Test.stopTest(); then assert results. For SOAP use WebServiceMock. Use StaticResourceCalloutMock or MultiStaticResourceCalloutMock for resource-based responses.
apex testing mocks
48

What is a test data factory and why use it? Medium

A utility class annotated @isTest that creates standard test records for reuse: @isTest public class TestDataFactory { public static List createAccounts(Integer n, Boolean doInsert) { List accs = new List(); for (Integer i = 0; i < n; i++) accs.add(new Account(Name = 'Test ' + i)); if (doInsert) insert accs; return accs; } } Benefits: consistent, maintainable data, easier bulk tests (200 records), fewer duplicated code lines. Never rely on org data (SeeAllData=false).
apex testing data-factory
49

What makes a good Apex unit test? Medium

- Tests positive, negative and bulk scenarios (200 records), and boundary conditions. - Creates its own data, uses System.runAs for different profiles, and tests permissions. - Uses assertions (Assert.areEqual, Assert.isTrue) that verify behaviour, not just coverage. - Uses Test.startTest/stopTest for limits and async code. - Tests exceptions with try/catch and asserting the message. - Is independent of order and data in the org. Coverage is a minimum; quality assertions prevent regressions.
apex testing assertions
50

How do you test code that depends on user permissions? Medium

Create a user with a specific profile or permission set in the test, then use System.runAs(user) to run the code in that user context to test sharing and FLS behaviour: User u = TestDataFactory.createUser('Standard User'); System.runAs(u) { /* call code and assert access results */ } Note runAs does not enforce mixed DML restrictions (setup and non-setup objects in the same transaction can be separated by runAs). Assign permission sets with insert of PermissionSetAssignment inside a runAs block.
apex testing runas
51

What is the mixed DML error and how do you avoid it? Medium

Mixed DML occurs when you insert or update setup objects (User, Group, PermissionSet, Profile, etc.) and non-setup objects (Account, Contact) in the same transaction. Solutions: separate into different transactions using @future methods, Queueable Apex, or in tests wrap setup DML in System.runAs(). Plan logic so that user and data creation are decoupled.
apex mixed-dml
52

What is a wrapper class and when is it used? Medium

A wrapper class combines multiple pieces of data (record plus extra fields) into one object, commonly used in Visualforce and LWC controllers for tables with checkboxes or computed values. public class AccountWrapper { public Account acc {get; set;} public Boolean selected {get; set;} public AccountWrapper(Account a) { acc = a; selected = false; } } In LWC, the @AuraEnabled method returns a list of wrappers with @AuraEnabled properties.
apex wrapper
53

How do you create and use custom exceptions? Medium

Extend the Exception class; the name must end with "Exception": public class InsufficientStockException extends Exception {} if (qty > stock) throw new InsufficientStockException('Only ' + stock + ' left'); Catch specifically and let unknown errors surface. In AuraEnabled methods throw AuraHandledException with a user-friendly message: throw new AuraHandledException('Unable to save'). Log errors in a custom object for diagnostics.
apex custom-exceptions
54

What are savepoints and rollbacks? Medium

Database.setSavepoint() marks a transaction state; Database.rollback(sp) reverts DML after it. Useful for testing multiple operations or preserving atomicity when partial failure should undo previous steps. Savepoint sp = Database.setSavepoint(); try { insert a; insert b; } catch (Exception e) { Database.rollback(sp); } Limits: savepoints count against the DML statement limit, and rolling back does not undo callouts, emails or ID consumption.
apex savepoint
55

How do sharing keywords and CRUD/FLS interact in an AuraEnabled controller? Medium

"with sharing" respects record visibility but not object or field permissions. To honour full user permissions use WITH USER_MODE in SOQL (and Database.insert(records, AccessLevel.USER_MODE)), or Security.stripInaccessible before DML and after queries. Example: List accs = [SELECT Id, Name FROM Account WITH USER_MODE LIMIT 10]; Always apply in code callable from UI or APIs. Use "without sharing" only for specific, justified system tasks, and document it.
apex security sharing
56

How does an LWC call Apex using @wire and imperative methods? Medium

Wire (reactive, cacheable): import getAccounts from '@salesforce/apex/AccountController.getAccounts'; @wire(getAccounts, { industry: '$industry' }) accounts; Re-runs when the reactive parameter changes. The Apex method must be @AuraEnabled(cacheable=true). Imperative (on demand, DML allowed): getAccounts({ industry: this.industry }).then(result => { this.data = result; }).catch(error => { this.error = error; }); Use for button actions, non-cacheable or DML methods. Refresh cached data with refreshApex.
lwc apex wire
57

What are the files in a Lightning Web Component and the main decorators? Medium

Files: myComponent.html (template), myComponent.js (class), myComponent.css, and myComponent.js-meta.xml (exposure and targets). Decorators: @api (public property/method), @track (deep reactivity, mostly unnecessary now), @wire (data reading). Lifecycle hooks: constructor, connectedCallback, renderedCallback, disconnectedCallback. Communication: parent to child via @api properties, child to parent via CustomEvent, unrelated components via Lightning Message Service.
lwc basics
58

How do components communicate in LWC? Medium

- Parent to child: public @api properties and methods. - Child to parent: dispatch a CustomEvent: this.dispatchEvent(new CustomEvent('select', { detail: id })) and handle with onselect in the parent template. - Sibling/unrelated: Lightning Message Service (publish/subscribe on a message channel) or pubsub patterns. - Data across components: Lightning Data Service shares cached record data. Prefer events with detail payloads and avoid direct DOM manipulation.
lwc events
59

Write a Visualforce page with a controller extension that adds a custom method to an Account page. Medium

Page: Contacts: {!total} Extension: public class AccountExt { private Account acc; public Integer total {get; set;} public AccountExt(ApexPages.StandardController sc) { acc = (Account) sc.getRecord(); } public void countContacts() { total = [SELECT COUNT() FROM Contact WHERE AccountId = :acc.Id]; } }
visualforce controller-extension
60

What is view state and how do you reduce it? Medium

View state stores the page state (controller variables, components) between requests in a hidden form field, limited to 170 KB. To reduce: mark variables transient (not serialised), use fewer variables and smaller collections, use apex:outputPanel with rerender instead of reloading, query only needed fields, use readonly="true" for reporting pages, remote actions/JavaScript remoting to avoid form posts, and paginate large lists. Monitor with Development Mode.
visualforce viewstate
61

How do apex:actionFunction, apex:actionSupport and apex:actionPoller differ? Medium

- actionFunction: defines a JavaScript function that calls a controller method and optionally rerenders regions; invoked from JS. - actionSupport: adds AJAX behaviour to another component's event (onchange, onclick) to call an action and rerender. - actionPoller: periodically calls a controller method (for example every 5 seconds) to refresh data. They use partial page refresh with rerender, status and oncomplete attributes.
visualforce actions
62

How do you generate a PDF with Visualforce? Medium

Set renderAs="pdf" in the apex:page tag: . Use simple CSS with @page rules for size and margins; avoid unsupported JavaScript. Common for invoices and quotes. Attach the PDF through Apex with PageReference.getContentAsPDF() and save as ContentVersion or email attachment.
visualforce pdf
63

What is PageReference and how is it used for navigation? Medium

PageReference represents a URL; controllers return it from action methods to navigate. Examples: return new PageReference('/' + acc.Id); return Page.MyPage; with parameters: pr.getParameters().put('id', recId); pr.setRedirect(true) forces a new request (clears view state). Use ApexPages.currentPage().getParameters().get('id') to read parameters.
visualforce pagereference
64

What are the benefits of Platform Cache? Medium

Platform Cache stores data in memory for faster access across transactions and users: Org Cache (shared across users) and Session Cache (per user session). Use for frequently read, rarely changing data such as configuration or API tokens. It reduces repeated SOQL queries and callouts. Define partitions and TTL; code uses Cache.Org.get/put with fallback logic when cache is empty.
apex custom-metadata cache
65

How do you publish and subscribe to platform events in Apex? Medium

Publish: EventBus.publish(new Order_Shipped__e(Order_Id__c = o.Id)); returns SaveResult. Subscribe: an Apex trigger on the event object (trigger OrderShippedTrigger on Order_Shipped__e (after insert) { for (Order_Shipped__e e : Trigger.new) { ... } }). Events are delivered after commit if "Publish After Commit" is chosen, retries with EventBus.RetryableException, and external clients subscribe via CometD or Pub/Sub API. Use for decoupled processes.
apex platform-events
66

How do you expose a custom REST API in Apex? Medium

Use @RestResource: @RestResource(urlMapping='/Accounts/*') global with sharing class AccountService { @HttpGet global static Account getAccount() { RestRequest req = RestContext.request; String id = req.requestURI.substringAfterLast('/'); return [SELECT Id, Name FROM Account WHERE Id = :id]; } @HttpPost global static Id createAccount(String name) { Account a = new Account(Name = name); insert a; return a.Id; } } Accessible at /services/apexrest/Accounts/. Secure with OAuth, permissions and input validation.
apex rest
67

When would you use the standard REST/SOAP API instead of custom Apex REST? Medium

Use standard APIs for CRUD, queries and bulk data (REST API, Bulk API 2.0, Composite API, SOAP) because they are maintained, documented and optimised. Create Apex REST endpoints only when you need custom business logic, a simplified contract or transactions combining several operations. Using standard APIs reduces code, tests and maintenance.
apex rest standard
68

Give examples of common String, Date and Math operations in Apex. Medium

String: 'Hello'.toUpperCase(), s.contains('ell'), s.split(','), String.join(list, ','), String.format('{0} - {1}', new List{'a','b'}), s.substring(0,3), s.isBlank(). Date: Date.today(), d.addDays(7), d.daysBetween(other), Date.newInstance(2025,1,31), Datetime.now().format('yyyy-MM-dd'). Math: Math.max(a,b), Math.round(x), Math.mod(a,b), Math.abs(x). Always check for null with String.isBlank and handle time zones using Datetime methods.
apex string date
69

What new Apex language features should developers know (switch, safe navigation, null coalescing)? Medium

- switch on: switch on stage { when 'Closed Won' { ... } when else { ... } } also for enums and sObject types. - Safe navigation operator ?.: String name = acc?.Owner?.Name; avoids NullPointerException. - Null coalescing ??: String label = input ?? 'Default'; - Apex Assert class (Assert.areEqual, Assert.isNotNull) and user mode DML/SOQL (AccessLevel.USER_MODE). - Inline SOQL for loops for large result sets.
apex switch
70

Why use SOQL for loops? Medium

for (List batch : [SELECT Id FROM Account]) { ... } retrieves records in chunks of 200, so the heap usage stays low and it can process large result sets without hitting heap limits; ordinary lists would load everything into memory. Use for loops with single sObject variable (for (Account a : [SELECT...])) for the same chunked behaviour with row-by-row access; DML should be done on lists outside the loop.
apex soql for-loop
71

How do you use Schema describe to build dynamic code? Medium

Schema.DescribeSObjectResult d = Account.SObjectType.getDescribe(); Map fields = d.fields.getMap(); boolean canEdit = fields.get('Industry').getDescribe().isUpdateable(); Schema.getGlobalDescribe() lists all objects (expensive, cache results). Use it for dynamic forms, field sets, field-level checks and building generic utilities, taking care with performance and governor limits (describe calls limit).
apex describe
72

What are field sets and how are they used in Visualforce? Medium

Field sets are groups of fields defined in Setup that admins can change without code. In Visualforce loop through them: . Developers use them in dynamic SOQL via fieldSet.getFields(). They provide flexibility for admin-managed layouts in Visualforce and Lightning components.
apex field-sets
73

What are Named Credentials and why use them? Medium

Named Credentials store the endpoint URL and authentication (password, OAuth, JWT, AWS signature) for external services; Apex references them with callout:Name. Benefits: no hard-coded secrets, no need for Remote Site Settings (with the new external credential model), tokens managed by Salesforce, and easier environment changes. Permissions are granted via external credential principals in permission sets.
apex named-credentials
74

How do you diagnose "Too many SOQL queries: 101" and CPU timeout errors? Medium

Review the debug log: look at "Number of SOQL queries" and CPU time sections; find queries in loops (including those in trigger handlers called per record), multiple triggers, flows and processes in the same transaction that add up. Fixes: bulkify, move queries outside loops, use maps, reduce redundant queries via caching, use asynchronous processing, optimise algorithms (nested loops O(n squared) replaced by maps O(n)), and consolidate automation on the object.
apex debugging limits
75

Describe the Selector, Service and Domain layers (Apex Enterprise Patterns) and why they help. Hard

- Selector layer: classes responsible only for SOQL queries (AccountSelector.selectByIds(ids)); central place for fields, ordering and security; easily mocked. - Service layer: business logic and transaction orchestration (AccountService.upgradeToPremium(ids)); callable by triggers, flows, controllers and APIs. - Domain layer: logic specific to a single object's records (validation, defaults) in a class wrapping a list of records, invoked by the trigger. Benefits: separation of concerns, reuse, unit tests with mocks (Apex Mocks/Stub API), consistent security and fewer governor problems. Cost: more classes and overhead for small projects; adopt where complexity and team size justify.
apex architecture patterns
76

How do you unit test code that depends on database access or services without using real data (Stub API)? Hard

Use dependency injection and interfaces: define IAccountSelector and inject it into the service. In tests supply a stub implementing System.StubProvider: public class SelectorStub implements System.StubProvider { public Object handleMethodCall(Object stubbedObject, String methodName, Type returnType, List paramTypes, List paramNames, List args) { if (methodName == 'selectByIds') return new List{ new Account(Name='Stub') }; return null; } } IAccountSelector sel = (IAccountSelector) Test.createStub(IAccountSelector.class, new SelectorStub()); Benefits: tests run faster without DML, no data setup, isolated logic tests. Also use TestVisible and mocks for callouts.
apex stub-api mocking
77

A trigger exceeds the CPU time limit when processing 200 records. How do you optimise it? Hard

1. Use the debug log with CPU timing (Profiling) or Apex Replay debugger to find hot spots. 2. Replace nested loops (O(n squared)) with maps keyed by ID/value. 3. Avoid repeated string concatenation in loops, use String.join; avoid Schema.getGlobalDescribe repeatedly (cache it). 4. Minimise SOQL queries and fetch only necessary fields; avoid querying in methods called per record. 5. Move heavy logic to asynchronous Queueable/Batch where real-time is not needed. 6. Consolidate automation (flows, process builders) that also consume CPU in the same transaction. 7. Use declarative updates (before-save flows) for simple field updates and cache static data in static variables or Platform Cache. Re-test with 200 and 2,000 records via batch.
apex performance cpu
78

How do you avoid heap size errors when processing large data? Hard

- Use SOQL for loops (chunks of 200) instead of storing large lists. - Query only required fields, not SELECT * equivalents. - Process in batches via Batch Apex (each execute has its own heap). - Release references (set variables to null) when done and avoid keeping big strings, blobs or JSON in memory; stream JSON using JSONParser and JSONGenerator. - Avoid storing duplicated collections; use maps carefully. - For files and callout responses, use the streaming approach or smaller pages (pagination). Heap limits: 6 MB synchronous, 12 MB asynchronous.
apex heap memory
79

How do you handle concurrency issues such as UNABLE_TO_LOCK_ROW and lost updates in Apex? Hard

UNABLE_TO_LOCK_ROW happens when concurrent transactions update related records that require the same lock (for example many children of one parent updating a roll-up). Mitigations: reduce batch size, process in serial mode, sort records by parent, retry logic in Queueable with a finalizer, avoid data skew, use FOR UPDATE for critical sections (short), and keep transactions small. Lost updates (two users editing the same record) can be avoided with optimistic locking: compare LastModifiedDate or a version field before update and throw an error if changed.
apex locking concurrency
80

How would you design an idempotent integration inbound endpoint that receives order updates from an ERP, possibly with duplicates and out of order? Hard

- Use an external ID (ERP_Order_Id__c) with upsert to avoid duplicates. - Include a message ID and store processed IDs (custom object or platform cache) to ignore duplicates. - Include a sequence number or timestamp (ERP_Version__c) and only apply the update if it is newer than the stored version (compare before upsert). - Make processing atomic with Savepoints and return clear status codes (200, 202, 409 conflict, 400 validation). - For high volume accept the payload, store it in a staging object or platform event, and process asynchronously through Queueable/Batch for resilience. - Log failures and implement retries with exponential backoff and a dead-letter process for manual handling. - Secure with OAuth and IP restrictions.
apex design idempotency
81

How do you design callouts from triggers and handle limits and uncommitted work pending errors? Hard

Callouts cannot run synchronously in triggers (they would block DML), so use an async method: @future(callout=true) or Queueable implementing Database.AllowsCallouts, invoked from the trigger with collected IDs. "You have uncommitted work pending" occurs when DML precedes a callout in the same transaction; reorder to callout first or run the callout in a separate async context. Respect 100 callouts per transaction and 120 seconds total timeout, and use Named Credentials with retry/ backoff and circuit-breaker logic for failures. For read-heavy API calls consider cache.
apex limits callouts
82

Describe the main security risks in Apex and Visualforce and how to mitigate them. Hard

- SOQL injection: use bind variables, escapeSingleQuotes, allow-lists. - Cross-site scripting (XSS): escape output in Visualforce (default HTML escaping on {! } but avoid escape="false"), use JSENCODE, HTMLENCODE, URLENCODE when embedding variables in JavaScript or URLs. - CSRF: Visualforce forms include anti-CSRF tokens; avoid state changes in constructors and GET requests. - Insecure CRUD/FLS or sharing bypass: use with sharing, WITH USER_MODE, stripInaccessible. - Exposed secrets: use Named Credentials/protected custom metadata, no hard-coded passwords. - Insecure endpoints: authentication and validation in REST services; limit data returned. Run Salesforce Code Analyzer (PMD) and security review checks.
apex security injection
83

How do you write tests for asynchronous Apex (batch, queueable, future, scheduled)? Hard

Wrap the async call between Test.startTest() and Test.stopTest(); the platform executes the async job synchronously at stopTest, then assert the results. Test.startTest(); Database.executeBatch(new AccountBatch(), 200); Test.stopTest(); System.assertEquals(200, [SELECT COUNT() FROM Account WHERE Description = 'Reviewed']); Batch tests run only one execute (limit of 1 batch scope in tests: up to the scope size), so keep test data within one batch. Queueable chaining is not executed in tests beyond the first job (Test.isRunningTest() or using finalizers); for scheduled classes call System.schedule within start/stop and verify CronTrigger. Use Test.setMock for callouts in these jobs.
apex mocking test
84

How do you analyse and optimise SOQL performance in Apex? Hard

- Use selective queries: filters on indexed fields (Id, Name, lookup/master-detail, external ID, unique, CreatedDate) that return under about 10 percent of records (first 1 million) or limit thresholds, to avoid full table scans. - Avoid negative operators (!=, NOT IN), leading wildcards (LIKE '%abc'), formula fields in WHERE and null checks on large data sets. - Use the Query Plan tool in Developer Console to see cost; request custom indexes or skinny tables. - Limit rows (LIMIT) and fields; use SOQL for loops; use aggregate queries instead of retrieving all data. - Consider Big Objects or external storage for historical data. Poor selectivity causes "Non-selective query against large object type" errors in triggers.
apex debug performance
85

Explain "Non-selective query against large object type (more than 200,000 rows)" and how to fix it. Hard

It occurs in triggers and synchronous contexts when a SOQL query on an object with more than 200,000 records lacks an indexed, selective filter, so the optimiser must scan the table. Fixes: add selective filters (indexed fields, narrow date range), use IDs from collections (WHERE Id IN :ids), ask Salesforce support for a custom index, avoid formula fields in filters, restructure logic into asynchronous processing (Batch Apex handles full scans through QueryLocator up to 50 million), or archive old data to reduce volume. Check Query Plan results for cost under 1.
apex debug error
86

Design an LWC and Apex solution for an editable data table of opportunities with inline editing, pagination and optimistic UI. Hard

- Apex: @AuraEnabled(cacheable=true) getOpportunities(Integer pageSize, Integer offset, String sortBy, String sortDir) using SOQL with LIMIT/OFFSET (for deep paging use keyset on Id/CreatedDate) and WITH USER_MODE; return a wrapper with records and total count. A non-cacheable @AuraEnabled saveOpportunities(List records) using Database.update with partial success and returns errors. - LWC: lightning-datatable with editable columns, onsave handler calling the imperative Apex, show lightning toast for success/errors, draft values to indicate unsaved changes, refreshApex or updateRecord from lightning/uiRecordApi for cache refresh. - Pagination controls with page size selection, sorting via onsort. - Security: CRUD/FLS enforcement, validation messages, bulk-safe update. - Test: Jest tests for the component and Apex tests (positive/negative/bulk).
apex lwc architecture
87

How do you unit test an LWC with Jest? Hard

Salesforce provides @salesforce/sfdx-lwc-jest. Create __tests__/myComponent.test.js, import createElement from 'lwc', create the element, append to document.body, and assert DOM output. Mock Apex methods with jest.mock('@salesforce/apex/Controller.method', () => ({ default: jest.fn() }), { virtual: true }), emit wire data with test wire adapters (registerApexTestWireAdapter), and flush promises (await Promise.resolve()). Verify events with jest.fn() handlers and clean up DOM after each test.
apex lwc jest
88

Describe a CI/CD pipeline for Salesforce developer projects. Hard

- Source in Git (feature branches, pull requests) using Salesforce DX project format. - Pipeline (GitHub Actions, Jenkins, Azure DevOps, Copado): on pull request create a scratch org or use a validation sandbox, deploy changed metadata (delta deployments with sfdx-git-delta), run Apex tests (RunLocalTests or specified), run static analysis (Salesforce Code Analyzer, PMD, ESLint) and LWC Jest tests. - Quality gates: coverage threshold (for example 85 percent), no critical code smells. - Merge to main triggers deployment to integration/UAT sandbox, then to production with manual approval; use quick deploy of validated packages. - Rollback plan: redeploy previous tag; backup metadata. - Environment config via named credentials and custom metadata; secrets in pipeline secrets store.
apex deployment ci
89

What are scratch orgs and how do they differ from sandboxes? Hard

Scratch orgs are disposable, source-driven Salesforce environments created from a definition file (config/project-scratch-def.json) via CLI (sf org create scratch). They contain only the features and settings declared, no data copy, and expire (default 7 days, max 30). Developers push and pull source with the project. Sandboxes are copies of production metadata (and data) that persist and are refreshed on a schedule. Scratch orgs support CI and modular development with unlocked packages, while sandboxes are for UAT and integration testing.
apex packaging dx
90

How would you design an event-driven architecture on Salesforce using Platform Events and Change Data Capture? Hard

- Define business events as Platform Events (Order_Created__e) with minimal payload plus IDs; publish from Apex, flows or external systems. - Consumers: Apex triggers (with checkpoints/retries), flows, LWC (empApi) and external subscribers via the Pub/Sub API (gRPC). - Use CDC for automatic change events (Account, custom objects) rather than custom polling; filter with enriched channels. - Ensure idempotency (replay IDs, de-duplication) and ordering expectations (events are ordered per channel but not transactional with consumers). - Monitor delivery limits (events per day/hour allocation) and handle failures with retry and dead-letter logging. - Benefits: decoupling, scalability and near-real-time integration. Trade-off: eventual consistency and additional monitoring.
apex architecture events
91

Design a solution to recalculate a financial summary on 5 million transaction records nightly without hitting limits. Hard

- Use Batch Apex with Database.QueryLocator for the transaction object (supports up to 50 million rows) with a scope size tuned (200 to 2,000 depending on CPU). - Aggregate within the batch using Maps keyed by account and accumulate into a Stateful map, or better, avoid state by writing partial summaries and aggregating via a final query (AggregateResult SOQL) in finish(). - Schedule through Schedulable at off-peak, chain batches by finish() using Database.executeBatch or Queueable. - Avoid locking: sort by parent ID and run serial where needed, minimise triggers on summary records. - Monitor with Apex Jobs, log failures to a custom object and send a summary email. - Alternative: use roll-up via Flow/DLRS or CRM Analytics for reporting rather than storing computed data.
apex design limits
92

Explain OAuth flows for Salesforce integrations and which to use for server-to-server. Hard

- Web Server flow (authorization code): user-interactive apps with a secret. - User-Agent flow: browser apps (less used). - JWT Bearer flow: server-to-server integrations with a certificate and pre-authorised connected app; no interaction. - Client Credentials flow: server-to-server using an integration user and client ID/secret (no user context otherwise). - Device and refresh token flows. For server-to-server use JWT Bearer or Client Credentials with a dedicated integration user with least-privilege permission set. Store keys securely and rotate certificates; restrict IPs with connected app policies.
apex integration oauth
93

Design a reusable error logging framework in Apex. Hard

- Custom object Error_Log__c (Class, Method, Message, Stack Trace, Record Id, Severity, User, Transaction ID). - Logger class with methods logException(Exception e, String context) that collects logs in a static list and commits them using Platform Events (Log_Event__e) so they survive transaction rollbacks and do not consume the main DML in a failing transaction. - Trigger/flow on the platform event inserts Error_Log__c records. - Include severity levels, correlation ID, optional notification to admins and retention policy (scheduled batch deletes old logs). - Provide an invocable method for flows to log faults. - Secure data (no sensitive information in logs) and add tests.
apex design error-handling
94

A trigger works in the sandbox but fails in production with "FIELD_CUSTOM_VALIDATION_EXCEPTION" in a batch load. What do you do? Hard

Production has additional validation rules, flows or duplicates not present in sandbox (or different data and permissions). Steps: reproduce with a copy of production data through a Full sandbox, check active validation rules and the order of execution, review debug logs with a trace flag on the integration user, identify which rule fires and which record fails, add a bypass (custom permission or custom metadata flag) for data migration, and update the trigger to use Database.insert(records, false) with error logging. Compare metadata between orgs and keep sandboxes refreshed.
apex debug troubleshooting
95

When would you use Bulk API 2.0 versus REST/Composite API and Apex for data loading? Hard

Bulk API 2.0 processes large CSV loads asynchronously (millions of records) with automatic batching and is ideal for migrations and scheduled loads. REST/Composite API suits real-time, smaller payloads (up to 200 subrequests in Composite, 200 records in sObject Collections) with immediate responses. Apex is for custom logic that needs transaction control or business rules. Considerations: governor limits, API call limits, error handling (success/failure results), relationships using external IDs and serial mode for lock avoidance.
apex design bulk-api
96

Write an Apex trigger that prevents deleting an Account that has open Opportunities, in a bulk-safe way. Hard

trigger AccountTrigger on Account (before delete) { AccountTriggerHandler.preventDelete(Trigger.old); } public class AccountTriggerHandler { public static void preventDelete(List oldList) { Set ids = new Map(oldList).keySet(); Set blocked = new Set(); for (AggregateResult ar : [SELECT AccountId a FROM Opportunity WHERE AccountId IN :ids AND IsClosed = false GROUP BY AccountId]) { blocked.add((Id) ar.get('a')); } for (Account acc : oldList) { if (blocked.contains(acc.Id)) acc.addError('Cannot delete an account with open opportunities.'); } } } One query for all accounts, no SOQL in loops, and addError blocks only affected records (others succeed with partial processing in Database.delete(false)).
apex interview scenario
97

Write Apex to create a follow-up task for every Opportunity moved to Closed Won, avoiding duplicates and being bulk-safe. Hard

public static void createTasks(List newOpps, Map oldMap) { List tasks = new List(); for (Opportunity o : newOpps) { Opportunity old = oldMap.get(o.Id); if (o.StageName == 'Closed Won' && old.StageName != 'Closed Won') { tasks.add(new Task(WhatId = o.Id, OwnerId = o.OwnerId, Subject = 'Send welcome kit', ActivityDate = Date.today().addDays(3))); } } if (!tasks.isEmpty()) insert tasks; } Called from an after update trigger; it compares old and new stage to run only on the transition, so repeated edits do not create duplicates. Test with 200 records (some transitioning, some not).
apex interview scenario
98

Write a test class for that opportunity task logic. Hard

@isTest private class OpportunityTaskTest { @isTest static void createsTaskOnTransition() { List opps = new List(); for (Integer i = 0; i < 200; i++) opps.add(new Opportunity(Name='O'+i, StageName='Prospecting', CloseDate=Date.today().addDays(30))); insert opps; for (Opportunity o : opps) o.StageName = 'Closed Won'; Test.startTest(); update opps; Test.stopTest(); System.assertEquals(200, [SELECT COUNT() FROM Task WHERE Subject = 'Send welcome kit']); // edit again: no new tasks update opps; System.assertEquals(200, [SELECT COUNT() FROM Task WHERE Subject = 'Send welcome kit']); } } Add a negative test (stage not Closed Won) and assert zero tasks.
apex interview scenario
99

How would you display a hierarchy of accounts (parent, children, grandchildren) in a Lightning component efficiently? Hard

SOQL cannot recurse, so query level by level. In Apex: fetch the root account, then loop: query children WHERE ParentId IN :currentLevelIds, up to a fixed depth (5 to 10) to bound queries, building a map of parent to children. Return a tree wrapper (id, name, children) as JSON. In LWC use lightning-tree or a recursive component. Alternatively use a custom field storing the full path or ultimate parent ID (maintained by trigger/flow) to fetch the whole hierarchy in one query: WHERE Ultimate_Parent__c = :rootId.
apex interview scenario
100

Explain how you would decide between Flow and Apex for a new requirement. Medium

Start declarative: if requirements can be met by Flow (record-triggered, scheduled, screen) with manageable complexity and volume, choose Flow for faster delivery and admin ownership. Choose Apex when: complex algorithms or data structures, high volumes needing bulk or batch control, transactional control (savepoints), advanced callouts, performance-critical logic, reuse across systems, sophisticated error handling or need for unit tests and version control. Hybrid: flows call invocable Apex for complex pieces. Evaluate maintainability, team skills, limits, testing, and governance.
apex interview design
Questions Breakdown
Easy 35
Medium 40
Hard 25
🎓 Master Salesforce Platform Developer I (Apex and Visualforce)

Join our live classes with expert instructors and hands-on projects.

Enroll Now

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators