SalesforceWizard

Salesforce interview questions and answers

1,743 Salesforce interview questions with answers in simple English, for freshers and experienced professionals. Pick your experience level or role below, or test yourself in a timed mock interview.

Start here

How Salesforce interviews work

Salesforce interviews follow similar rounds around the world, whether at a consulting partner such as Accenture, Deloitte or TCS, at Salesforce itself, or at a company that uses Salesforce. Knowing them tells you what to prepare.

  1. Screening call. A recruiter checks your experience, certifications, notice period and salary expectations.
  2. Technical round 1. Core concepts for your role: security and automation for admins; Apex, SOQL, triggers and LWC for developers.
  3. Technical round 2 or scenario round. Real problems: "How would you design this?" or "What would you do if this broke in production?" Experienced candidates get more design and integration questions.
  4. Managerial or behavioural round. Your projects, your role in them, how you handle deadlines, clients and team members. In the US, UK and Europe this is often structured around past examples ("Tell me about a time when…").
  5. HR or recruiter round. Salary, start date or notice period, and fit. Some employers add a take-home exercise, a live build or a client interview for project roles.

Freshers usually get more definitions and basics. From about three years of experience, expect most questions to be scenarios built on your own projects. Read the scenario-based questions and the company-wise questions for examples.

Recent interview questions (company-wise)

Questions candidates report from recent interviews at TCS, Infosys, Accenture, Cognizant, Capgemini, the Big 4 and more.

General Salesforce questions

Fundamentals that come up in screening rounds for every role.

0 of 217 reviewed

General

01

What is Salesforce and how is it used in organizations?

BeginnerGeneral

Salesforce is a cloud-based CRM platform that helps businesses manage customer relationships, sales, and operations. It centralizes data like leads, accounts, and opportunities in one place. Teams use it to track interactions, automate processes, and improve customer experience. Since it's cloud-based, users can access it from anywhere. It's widely used across sales, service, marketing, and more.

02

What are the key components of Salesforce architecture?

BeginnerGeneral

Salesforce is built on a multi-tenant architecture, meaning multiple customers share the same infrastructure securely. Key components include objects, fields, records, metadata, and the platform services like Apex and APIs. It also has a detailed security model. Everything is metadata-driven, so changes don't affect the core system. This makes customization fast and scalable.

03

What is a multi-tenant architecture?

BeginnerGeneral

Multi-tenancy means multiple customers share the same application and infrastructure. Each customer's data is isolated and secure. It allows Salesforce to deliver updates to everyone at once. This reduces maintenance effort for customers. It also makes the platform cost-efficient and highly scalable.

04

What are standard and custom objects?

BeginnerGeneral

Standard objects are pre-built, like Account, Contact, and Opportunity. Custom objects are created by users to meet specific business needs. For example, a company might create a 'Project' object. Both can have fields, relationships, and automation. Custom objects behave just like standard ones.

05

What is metadata in Salesforce?

BeginnerGeneral

Metadata defines the structure of the application, like objects, fields, layouts, and workflows. Instead of storing data, it describes how data is organized. Salesforce uses metadata to deploy changes across environments. This makes development flexible and easy to migrate.

06

What is the difference between SaaS, PaaS, and IaaS?

BeginnerGeneral

Salesforce mainly operates as SaaS (Software as a Service), providing ready-to-use applications. It also offers PaaS via the Force.com platform for building custom apps. IaaS is about infrastructure, which Salesforce manages internally. Users mostly interact with SaaS and PaaS layers.

07

What is CRM and why is it important?

BeginnerGeneral

CRM stands for Customer Relationship Management. It helps businesses manage interactions with customers and prospects. It improves sales tracking, customer service, and marketing efforts. With CRM, companies can make data-driven decisions. It also enhances customer satisfaction.

08

What is the role of AppExchange?

BeginnerGeneral

AppExchange is Salesforce's marketplace for apps and integrations. Users can install pre-built solutions instead of building from scratch. It saves time and effort. Many apps are industry-specific. It's widely used in real-world implementations.

09

What are environments in Salesforce?

BeginnerGeneral

Salesforce provides environments like Developer, Sandbox, and Production. Sandboxes are used for testing and development. Production is the live system. This separation ensures safe deployments. It helps avoid direct changes in live data.

10

What is a record in Salesforce?

BeginnerGeneral

A record is a single instance of an object, like one Account or Contact. It stores data in fields. Users interact with records daily. Records are the core data units in Salesforce. They can be created, updated, and deleted.

11

What is the difference between logical and physical data model in Salesforce?

IntermediateGeneral

Logical defines relationships and structure (objects, relationships), while physical includes actual implementation (fields, indexes, storage).

12

What is schema builder used for?

IntermediateGeneral

A visual tool to design and manage objects, fields, and relationships in a graphical format.

13

Explain lookup vs master-detail in terms of behavior.

IntermediateGeneral

Lookup is loosely coupled; master-detail enforces dependency, cascade delete, and roll-ups.

14

What is data skew and why is it problematic?

IntermediateGeneral

Occurs when many records relate to one parent, causing performance and locking issues.

15

What is selective query in Salesforce?

IntermediateGeneral

A query that uses indexed fields to return results efficiently under large data volumes.

16

What are external objects?

IntermediateGeneral

Objects that map to external data sources using OData without storing data in Salesforce.

17

What is a junction object?

IntermediateGeneral

A custom object used to create many-to-many relationships via two master-detail fields.

18

What is skinny table?

IntermediateGeneral

A performance optimization feature that creates a denormalized table for frequently accessed fields.

19

What is deferred sharing calculation?

IntermediateGeneral

A way to delay sharing rule recalculations during large data operations.

20

What is the difference between big objects and standard objects?

IntermediateGeneral

Big objects handle massive data volumes with limited querying; standard objects support full functionality.

21

How do you design a scalable data model for millions of records?

AdvancedGeneral

Use indexing, partitioning, archiving strategy, avoid data skew, and design selective queries.

22

What is the impact of ownership skew?

AdvancedGeneral

Large number of records owned by one user causes locking and sharing recalculation issues.

23

How does Salesforce indexing work internally?

AdvancedGeneral

Uses selective indexes (standard/custom) and query optimizer to decide execution path.

24

What are polymorphic relationships?

AdvancedGeneral

Fields like WhoId/WhatId that reference multiple object types.

25

Explain multi-org strategy vs single-org strategy.

AdvancedGeneral

Single-org simplifies management; multi-org improves isolation but increases integration complexity.

26

What is large data volume (LDV) strategy?

AdvancedGeneral

Includes archiving, indexing, query optimization, async processing.

27

How do you handle record locking issues?

AdvancedGeneral

Use smaller transactions, avoid parent updates, use async processing.

28

What is eventual consistency in Salesforce?

AdvancedGeneral

Some async operations (like sharing recalculation) may not reflect immediately.

29

What is platform cache?

AdvancedGeneral

In-memory caching to improve performance for frequently accessed data.

30

How do you design multi-currency applications?

AdvancedGeneral

Use advanced currency management and dated exchange rates.

Administration

31

What does a Salesforce Administrator do?

BeginnerAdministration

An admin manages users, security, and system configuration. They create objects, fields, and automation tools. Admins ensure users have the right access. They also maintain data quality. In real projects, admins are the backbone of system management.

32

What is a profile in Salesforce?

BeginnerAdministration

A profile controls what users can do in Salesforce. It defines object permissions, field access, and system permissions. Every user must have one profile. Profiles ensure proper access control. They are essential for security.

33

What is the difference between profile and role?

BeginnerAdministration

Profiles control permissions, while roles control data visibility. Roles define hierarchy and record access. For example, managers can see their team's data. Profiles define actions, roles define access scope. Both work together.

34

What is a permission set?

BeginnerAdministration

Permission sets extend user permissions without changing profiles. They are useful for temporary or additional access. For example, giving API access to a few users. They provide flexibility. Multiple permission sets can be assigned to one user.

35

What is a validation rule?

BeginnerAdministration

Validation rules ensure data quality by enforcing conditions. They prevent incorrect data from being saved. For example, making a field mandatory based on criteria. They improve data accuracy. Users get error messages if rules fail.

36

What is a workflow rule?

BeginnerAdministration

Workflow rules automate simple actions like email alerts, field updates, and tasks. They trigger based on record changes. Though being retired in favor of Flows, they're still widely used. They simplify repetitive tasks.

37

What are record types?

BeginnerAdministration

Record types let you offer different page layouts and picklist values for different users. For example, different opportunity layouts for sales vs. partner teams. They customize the user experience per business process.

38

What is a page layout?

BeginnerAdministration

Page layouts control which fields, buttons, and related lists appear on a record page. Admins assign layouts by profile. They help users see only relevant information. Layouts improve productivity.

39

What are sharing rules?

BeginnerAdministration

Sharing rules extend record access beyond the org-wide defaults. They grant access to groups or roles. Criteria-based rules share records matching specific conditions. Owner-based rules share based on ownership.

40

What is a report type in Salesforce?

BeginnerAdministration

Report types define which objects and fields are available in reports. Standard report types come built-in. Custom report types let you combine objects. They are the foundation of reporting.

41

What is the difference between OWD and sharing rules?

IntermediateAdministration

OWD sets the baseline access level for all records. Sharing rules open up access beyond OWD. OWD restricts, sharing rules extend. They work together to control data visibility.

42

How do you handle field-level security?

IntermediateAdministration

Field-level security controls which fields users can see and edit. It's set per profile or permission set. It works alongside page layouts. Even if a field is on the layout, FLS can hide it.

43

What is a permission set group?

IntermediateAdministration

A collection of permission sets assigned together. It simplifies permission management. You can mute specific permissions within the group. It's recommended over single permission sets for complex setups.

44

What are dynamic forms?

IntermediateAdministration

Dynamic forms let you place fields anywhere on Lightning record pages. They replace traditional page layouts for flexibility. You can add visibility rules per field. This provides a highly customized user experience.

45

What is the difference between lookup filter and validation rule?

IntermediateAdministration

Lookup filters restrict which records can be selected in a lookup field. Validation rules check data on save. Lookup filters work at the UI level, validation rules at the data level.

46

How do you implement territory management?

IntermediateAdministration

Territory management assigns accounts to territories based on rules. It supports complex sales structures. Enterprise Territory Management is the latest version. It works alongside the role hierarchy.

47

What is data loader and when do you use it?

IntermediateAdministration

Data Loader is a tool for importing, exporting, updating, and deleting large volumes of data. Use it for operations over 50,000 records. It supports CSV files and can be automated via command line.

48

What are custom metadata types?

IntermediateAdministration

Custom metadata types store configuration data that can be deployed. Unlike custom settings, they're metadata. They're perfect for app configuration, mappings, and business rules. They can be packaged and deployed.

49

How do you set up multi-factor authentication?

IntermediateAdministration

MFA adds a second verification step during login. Salesforce requires MFA for all users. Admins configure it via Session Settings. Users can use authenticator apps or security keys.

50

What is the difference between custom settings and custom metadata types?

IntermediateAdministration

Custom settings store org-specific data accessible in code. Custom metadata types are deployable configuration. Custom metadata can be packaged; custom settings cannot. Use metadata types for app config, settings for runtime data.

51

How do you design a complex approval process?

AdvancedAdministration

Map out the business process first. Use multiple steps with different approvers. Add entry criteria and approval actions. Consider parallel approvals and delegated approvers. Test thoroughly with different scenarios.

52

How do you handle org-wide email management?

AdvancedAdministration

Configure organization-wide email addresses for different departments. Set up email deliverability settings. Use email relay for custom domains. Monitor email logs for issues.

53

What is the Salesforce Shield platform?

AdvancedAdministration

Shield provides enhanced security features including Platform Encryption, Event Monitoring, and Field Audit Trail. It's an add-on for compliance-heavy industries. It encrypts data at rest with tenant-specific keys.

54

How do you plan a data migration strategy?

AdvancedAdministration

Assess source data quality. Map fields between systems. Plan the loading order (accounts before contacts). Use sandbox for testing. Validate data after migration with reports.

55

What is the impact of enabling person accounts?

AdvancedAdministration

Person accounts merge Account and Contact into one record for B2C scenarios. Once enabled, it cannot be disabled. It affects data model, reporting, and integrations significantly.

56

A user reports they can't see a field on a record page. How do you troubleshoot?

IntermediateAdministration

Check field-level security on the user's profile and permission sets first. Then verify the field is on the page layout assigned to their profile/record type. Also check if it's hidden by a dynamic form visibility rule. Finally, ensure the field has a value if it's conditionally displayed.

57

You need to prevent duplicate records from being created. What's your approach?

IntermediateAdministration

Use duplicate rules and matching rules for declarative prevention. Add Apex trigger logic for complex scenarios. Consider using external ID fields for integration-created records. Implement fuzzy matching for name-based deduplication.

58

A sales team needs different views of the same object. How do you implement this?

IntermediateAdministration

Use record types for different page layouts and picklist values. Create role-based list views. Use dynamic forms with visibility rules. Consider Lightning App pages specific to different user groups.

59

How would you design a complex approval process with multiple conditional paths?

AdvancedAdministration

Map the business process flow first. Use entry criteria to route to different approval steps. Set up parallel approvers where possible. Use initial and final submission actions. Consider using Flow for very complex scenarios that exceed approval process capabilities.

Development

60

What is Apex in Salesforce?

BeginnerDevelopment

Apex is Salesforce's proprietary programming language. It's similar to Java. Developers use it for complex business logic, triggers, and integrations. It runs on Salesforce servers. It's strongly typed and object-oriented.

61

What is a trigger in Salesforce?

BeginnerDevelopment

A trigger is Apex code that runs before or after DML operations. It automates actions on record changes. Triggers can validate data, update related records, or call external services. They're powerful but should follow best practices.

62

What is the difference between SOQL and SOSL?

BeginnerDevelopment

SOQL queries one object at a time (like SQL). SOSL searches across multiple objects using text search. SOQL is for precise queries; SOSL is for keyword searches. Both have governor limits.

63

What are governor limits?

BeginnerDevelopment

Governor limits are runtime restrictions that prevent any single tenant from monopolizing shared resources. Examples include 100 SOQL queries per transaction, 150 DML statements, and 6 MB heap size. They enforce efficient coding.

64

What is a Visualforce page?

BeginnerDevelopment

Visualforce is a markup language for building custom UI pages. It uses a tag-based syntax similar to HTML. It's being replaced by Lightning Web Components but is still widely used. It works with Apex controllers.

65

What is Lightning Web Components (LWC)?

BeginnerDevelopment

LWC is Salesforce's modern UI framework built on web standards. It uses JavaScript, HTML, and CSS. It's faster and more efficient than Aura components. LWC is the recommended approach for new development.

66

What is a test class in Salesforce?

BeginnerDevelopment

Test classes verify that Apex code works correctly. They simulate real scenarios. They are mandatory for deployment; you need at least 75% code coverage. Test classes should cover positive, negative, and bulk scenarios.

67

What is the difference between before and after triggers?

BeginnerDevelopment

Before triggers run before a record is saved to the database. They're used for validation and field updates. After triggers run after the record is saved. They're used when you need the record ID or to update related records.

68

What is a batch Apex class?

BeginnerDevelopment

Batch Apex processes large volumes of records asynchronously. It breaks data into chunks (default 200 records). It implements Database.Batchable interface. Use it for operations exceeding governor limits.

69

What are Salesforce APIs?

BeginnerDevelopment

Salesforce provides REST API, SOAP API, Bulk API, Streaming API, and Metadata API. They enable integration with external systems. REST API is the most commonly used. Each API has specific use cases and limits.

70

What is bulkification in Apex?

IntermediateDevelopment

Writing code that handles multiple records efficiently instead of one at a time. Use collections (Lists, Sets, Maps) instead of single records. This prevents hitting governor limits. It's a fundamental best practice.

71

What is the difference between Apex managed sharing and declarative sharing?

IntermediateDevelopment

Declarative sharing uses OWD, roles, and sharing rules. Apex managed sharing uses code to create share records. Use Apex sharing for complex scenarios that can't be handled declaratively.

72

How do you handle callouts in Apex?

IntermediateDevelopment

Use HttpRequest and HttpResponse classes. Mark methods with @future(callout=true) for async callouts. Add remote site settings for the endpoint. Handle timeouts and errors gracefully.

73

What is a wrapper class?

IntermediateDevelopment

A custom class that combines multiple data types into a single object. Used in Visualforce for displaying complex data. Also useful in LWC for structured data passing.

74

What is the difference between @future and Queueable?

IntermediateDevelopment

@future is simpler but limited: no chaining, no complex types. Queueable supports chaining, complex parameters, and monitoring. Use Queueable for most async needs.

75

How do you implement error handling in Apex?

IntermediateDevelopment

Use try-catch-finally blocks. Create custom exception classes. Log errors to custom objects. Use Database.SaveResult for partial DML operations. Always handle null references.

76

What is Platform Events?

IntermediateDevelopment

Platform Events enable event-driven architecture in Salesforce. They publish and subscribe to events in real-time. They work across Apex, Flows, and external systems. They're ideal for loosely coupled integrations.

77

What is the difference between static and instance methods?

IntermediateDevelopment

Static methods belong to the class and are called without an instance. Instance methods require an object. Static methods can't access instance variables. Use static for utility methods.

78

How do you optimize SOQL queries?

IntermediateDevelopment

Use selective filters on indexed fields. Avoid querying in loops. Use relationship queries instead of multiple queries. Limit fields to what's needed. Use WHERE clauses effectively.

79

What is Apex Enterprise Patterns?

AdvancedDevelopment

Design patterns for organizing large Apex codebases. Includes Service Layer, Domain Layer, Selector Layer, and Unit of Work. They promote separation of concerns. They make code testable and maintainable.

80

How do you design a trigger framework?

AdvancedDevelopment

Create a handler interface and dispatcher class. One trigger per object that delegates to the handler. Support before/after, insert/update/delete. Include recursion control and bypass mechanisms.

81

What is the difference between synchronous and asynchronous Apex?

AdvancedDevelopment

Synchronous runs immediately in the user's context with standard limits. Asynchronous runs in background with higher limits. Types include @future, Queueable, Batch, and Scheduled. Choose based on volume and timing needs.

82

How do you handle large data volumes in Apex?

AdvancedDevelopment

Use Batch Apex for processing. Implement selective queries. Use Platform Cache for frequently accessed data. Consider async patterns. Monitor heap size and query performance.

83

What is Salesforce DX and how does it change development?

AdvancedDevelopment

Salesforce DX is a modern development experience. It uses source-driven development with scratch orgs. CLI-based tooling enables automation. It integrates with Git for version control. It's the recommended development approach.

84

You need to update 5 million records. What approach do you take?

AdvancedDevelopment

Use Batch Apex with an appropriate batch size (200-2000). Consider using the Bulk API if coming from external system. Run during off-peak hours. Monitor for governor limits. Use Database.Stateful if you need to track state across batches.

85

Your Apex trigger is hitting governor limits. How do you fix it?

IntermediateDevelopment

Move SOQL queries and DML operations outside of loops. Use collections (Maps, Lists, Sets) for data processing. Implement a trigger handler pattern. Consider moving to asynchronous processing for heavy operations. Profile the code to identify bottlenecks.

86

What is the Singleton design pattern in Apex and when do you use it?

IntermediateDevelopment

CONCEPT ANSWER The Singleton pattern ensures that a class has only one instance throughout the entire transaction and provides a global point of access to it. We implement it using a private static variable that holds the instance. The constructor is private so no external code can instantiate it directly. A public static getInstance() method checks if the instance is null: creates it if so, returns it otherwise.

87

What is the Trigger Handler pattern and why is it important?

AdvancedDevelopment

CONCEPT ANSWER The Trigger Handler pattern moves all business logic out of the trigger file and into a dedicated handler class. The trigger itself becomes a thin dispatcher. Without this pattern triggers become large, unmaintainable files where multiple developers cause merge conflicts. Logic cannot be unit tested without firing DML. The same logic cannot be reused from other contexts like REST APIs or batch jobs. The pattern: create OpportunityTriggerHandler with static or instance methods for each trigger event; beforeInsert, afterUpdate etc.

88

What is the Service Layer pattern and why should business logic not live in the trigger handler?

AdvancedDevelopment

CONCEPT ANSWER The Service Layer contains all business logic for a domain, for example OpportunityService, completely independent of how it was invoked. The trigger handler knows about trigger context. The service layer does not. Service methods are context-agnostic; they accept data, execute logic, return results. They do not know whether they were called from a trigger, an LWC, a REST API, or a batch job. This is critical in enterprise applications where the same business rule is triggered from multiple entry points.

89

What is the Selector (Repository) pattern? Why should SOQL not be written directly in service classes?

AdvancedDevelopment

BEST PRACTICE ANSWER The Selector pattern creates a dedicated class responsible for all SOQL queries for a specific object: OpportunitySelector, ContactSelector etc. Without a selector, the same query is scattered across 10 service classes. Adding a new field or enforcing FLS requires updating 10 locations. One missed location becomes a bug or security vulnerability. With a Selector there is one place for all queries. Security (WITH USER_MODE) is applied consistently in one place. Queries are named descriptively making code self-documenting.

90

What is trigger recursion and how do you prevent it?

IntermediateDevelopment

CONCEPT ANSWER Trigger recursion occurs when a trigger fires, performs DML that updates a record, and that update re-fires the same trigger: creating an infinite loop until governor limits are hit. Most common cause: an after-update trigger that calculates something and updates the same object it fired on. Prevention 1: Static Boolean flag: a static Boolean in a utility class holds its value for the entire transaction. Set it to true on first entry, skip execution if already true. Prevention 2: Static Set of Ids: more granular than boolean. Track which Ids have been processed.

91

What are the 6 core best practices for writing Apex triggers?

IntermediateDevelopment

BEST PRACTICE ANSWER One: One trigger per object. Multiple triggers fire in unpredictable order. Consolidate all logic into one trigger per object. Two: Thin trigger, fat handler. No business logic inside the trigger file. Trigger only calls a handler class. Three: Always bulkify. Never assume a trigger fires for one record. Always treat Trigger.new as a list. No SOQL or DML inside loops. Four: Correct trigger events. Use before insert/update for field manipulation: record not yet saved, no DML needed. Use after insert/update for operations needing record Ids or related object updates.

92

Mass import of 500 Contacts via Data Loader hits governor limit errors. The trigger creates a Task per Contact. How do you fix it?

AdvancedDevelopment

The root cause is DML inside a loop. For 500 contacts the trigger is calling insert task 500 times: the DML limit is 150. Immediate fix: collect all Task records in a List inside the loop and do one bulk insert after the loop. Also check for @future calls per record: the limit is 50 per transaction. 500 records will fail. Switch to Queueable with batching. Check for any workflow rules or process builders on Contact that fire additional DML; they share the same transaction limits.

93

What are the most important governor limits every Apex developer must know?

IntermediateDevelopment

CONCEPT ANSWER Salesforce enforces runtime limits to prevent any single tenant from monopolizing shared resources. SOQL: 100 synchronous queries per transaction, 200 async. Query result rows: 50,000. Heap: 6 MB sync, 12 MB async. DML: 150 DML statements, 10,000 DML rows per transaction. CPU: 10,000 ms synchronous, 60,000 ms asynchronous. Callouts: 100 callouts, 120 seconds total callout time per transaction. Async: 50 @future calls per transaction. 250,000 async jobs in queue daily. The most commonly hit in production: SOQL in loops (100 limit) and DML in loops (150 limit).

94

Describe the correct bulkification pattern in Apex with a practical example?

IntermediateDevelopment

BEST PRACTICE ANSWER Bulkification means writing code that processes 1 or 10,000 records with equal correctness and efficiency. Pattern: Collect → Query → Map → Process in memory → DML. Step 1 Collect: gather all foreign-key Ids from the input list into a Set before any SOQL. Step 2 Query: one SOQL with IN :idSet; never query inside a loop. Step 3 Map: store query results in Map<Id,SObject> for O(1) lookup. Step 4 Process: iterate the input list, use map.get() to find related data, build output collections.

95

Your batch job processes 1 million records and hits heap size errors in production. How do you diagnose and fix it?

AdvancedDevelopment

Heap limit is 12 MB for async Apex including batch. 1 million records with broad field selection fills heap quickly. Fix 1: Reduce batch scope size. Default is 200; set it to 50 or even 10 using Database.executeBatch(job, 50). Fewer records in memory per execute() call. Fix 2: Query only necessary fields. SELECT Id, Status__c instead of SELECT all fields reduces per-record heap footprint significantly. Fix 3: Avoid accumulating data across execute() calls. Instance variables that grow between batches cause heap to increase with each scope. Process and clear within each execute().

96

What is CPU time governor limit and what patterns cause it to spike?

AdvancedDevelopment

BEST PRACTICE ANSWER CPU time limit is 10,000 ms synchronous and 60,000 ms asynchronous. Salesforce measures CPU consumed by Apex code execution only: time waiting for SOQL results or callout responses does not count. Pattern 1: Nested loops: O(n²) complexity. If a trigger processes 200 records and for each record loops through another 200-item list, that is 40,000 iterations. Fix: replace inner loops with Map lookups; O(1) per access. Pattern 2: String operations in loops: String concatenation creates new String objects each iteration because Strings are immutable.

97

What are the 6 most common SOQL anti-patterns and how do you fix each?

IntermediateDevelopment

CONCEPT ANSWER 1. SOQL in a loop: the most common mistake. Fix: collect Ids into Set, one SOQL with IN clause, store in Map. 2. Selecting every field (for example FIELDS(ALL) in tools): querying all fields when 2-3 are needed. Wastes heap. Fix: SELECT only fields actually used. 3. Missing WHERE on large objects: querying millions of rows without a filter. Fix: always filter on indexed fields. 4. Non-selective queries: WHERE clause uses a non-indexed field on a large object. Salesforce may throw a row count error. Fix: use indexed fields (Id, Name, external Id, lookup fields), add LIMIT, or request a custom index. 5.

98

What is the difference between static SOQL and dynamic SOQL (Database.query)? When is each appropriate?

AdvancedDevelopment

BEST PRACTICE ANSWER Static SOQL is written inline with square brackets and validated at compile time. Salesforce checks field names, object names, and syntax during compilation. This is the default choice: safer, cleaner, and easier to read. Dynamic SOQL uses Database.query() with a String built at runtime. Only validated at runtime. Use it when fields, objects, or conditions must be determined dynamically: user-selectable columns, optional search filters, multi-object queries.

99

What is the difference between List, Map, and Set for storing SOQL results? When do you use each?

IntermediateDevelopment

CONCEPT ANSWER List<SObject> is the default: ordered, allows duplicates. Use it for sequential processing and DML operations. DML accepts Lists not Sets. Map<Id,SObject> wraps SOQL results in new Map<Id,SObject>([...]). Provides O(1) lookup by Id. Use it whenever you need to find a record by Id inside a loop: the most common trigger pattern. Set<Id> stores unique Ids only. Use it to collect parent Ids before a SOQL query (auto-deduplicates), to check membership with contains(), or to deduplicate Id lists. O(1) lookup.

100

What is SOQL for loops and when should you use them?

AdvancedDevelopment

CONCEPT ANSWER A SOQL for loop: for(SObject s : [SELECT...]): processes query results in chunks of 200 records at a time instead of loading all results into heap at once. Each chunk is automatically discarded from memory after processing. Use SOQL for loops when querying large result sets that would exceed heap size if loaded into a List at once. They are the Apex equivalent of streaming a query. Regular List<SObject> = [SELECT...] loads ALL results into heap immediately. For 50,000 records this can easily exceed the 6 MB heap limit.

101

What is the difference between DmlException, QueryException, and AuraHandledException?

IntermediateDevelopment

CONCEPT ANSWER DmlException is thrown when a DML operation fails: required field missing, validation rule violation, record locked, duplicate blocked. It exposes getDmlMessage(i) and getDmlIndex(i) to get per-record error details. QueryException is thrown when a SOQL query expecting one result returns zero or more than one: the too many rows error. Fix: always query into a List and check size() before accessing index 0. AuraHandledException is special: when thrown in an @AuraEnabled method it propagates the message cleanly to LWC as error.body.message.

102

How do you create and use custom exceptions in Apex? Why are they better than generic Exception?

IntermediateDevelopment

CONCEPT ANSWER Custom exceptions extend the Exception class. Convention: suffix with Exception. They can be inner classes or standalone classes. Advantage of custom exceptions: specificity. A catch(Exception e) cannot distinguish a business rule violation from a system error. Custom exceptions allow different handling per error type: retry for PaymentException, user message for ValidationException, admin alert for SystemException. Custom exceptions can carry extra properties, error codes, record Ids, lists of validation messages, that generic exceptions cannot.

103

What is the difference between try-catch-finally and Database.Savepoint? When do you use each?

AdvancedDevelopment

BEST PRACTICE ANSWER Try-catch-finally controls exception flow. The catch block runs on exception. The finally block always runs: perfect for cleanup like resetting loading states or flushing logs. It does NOT roll back DML that already committed. Database.Savepoint is for transaction rollback; it undoes all DML performed since the savepoint was set. Essential when multiple DML steps must all succeed or all fail together: atomicity. Use try-catch-finally for: error handling, resource cleanup, loading state management, translating exceptions to user messages.

104

You process records in a loop where one record's DML failure must not stop others from processing. How do you implement this?

IntermediateDevelopment

Standard try-catch inside a loop rolls back the whole transaction on failure, not what we want. The solution is Database.insert/update/upsert with allOrNothing=false. This processes each record independently. Successes commit, failures do not, but processing continues for all records. The method returns List<Database.SaveResult> with one result per record. We iterate results, check isSuccess(), and collect errors from getErrors() for failed records. We log all failures to a custom Error_Log__c object with record Id and error message, allowing ops teams to review and retry failed records.

105

How do you implement a centralized error logging framework in Apex?

AdvancedDevelopment

BEST PRACTICE ANSWER A centralized error logging framework ensures all exceptions across the org are captured consistently, stored durably, and queryable for operations teams. Create a singleton Logger class (using Singleton pattern) that accumulates log entries in a List during the transaction. Using a singleton prevents multiple SOQL/DML calls for logging. At the end of critical operations, or in finally blocks, call Logger.getInstance().flush() which does one bulk insert of all accumulated logs. Log levels: INFO, WARNING, ERROR, CRITICAL.

106

What is the difference between CRUD, FLS, and Sharing in Salesforce? How does Apex handle each by default?

IntermediateDevelopment

CONCEPT ANSWER CRUD controls whether a user can perform object-level operations: Create, Read, Update, Delete. Defined on profiles and permission sets. FLS controls which fields on an object a user can view or edit. Also defined on profiles and permission sets. Sharing controls which records a user can see: record-level access. Controlled through OWD, sharing rules, role hierarchy, and manual sharing. By default Apex runs in system context and ignores all three. An Apex class can read any field, any object, and any record regardless of the running user's permissions.

107

What is the difference between with sharing, without sharing, and inherited sharing? What are the risks of each?

AdvancedDevelopment

BEST PRACTICE ANSWER with sharing enforces the running user's sharing rules. Records outside the user's access are excluded from SOQL. Use this for all @AuraEnabled classes and REST resources: safest default for user-facing code. without sharing ignores sharing rules. All records are accessible regardless of user permissions. Use ONLY for backend automation: batch jobs, scheduled jobs, admin-only service classes. Never use in user-triggered code: data exposure risk. inherited sharing uses the sharing context of the calling code. If called from a with sharing class it enforces sharing.

108

A user sees data in LWC that they should not have access to. The Apex class is marked with sharing. What else could cause this?

AdvancedDevelopment

with sharing enforces record-level sharing rules but does NOT enforce FLS. The user can see all fields on their accessible records even if FLS restricts certain fields. Cause 1: FLS not enforced: SOQL returns restricted fields because with sharing does not check FLS. Fix: add WITH USER_MODE to SOQL or call Security.stripInaccessible(AccessType.READABLE, results) before returning data.

109

What is Apex Managed Sharing? When would you use it over standard sharing rules?

IntermediateDevelopment

CONCEPT ANSWER Apex Managed Sharing allows Apex code to programmatically create, update, or delete sharing records: the Share objects like AccountShare, OpportunityShare, or custom object Share records. Use Apex Managed Sharing when sharing requirements are too dynamic or complex for declarative sharing rules. Examples: share a record with a specific user only after a specific approval step completes, share a record with a team that is stored in a custom object relationship rather than roles, or grant temporary time-based access.

110

What are the differences between List, Set, and Map in Apex? When do you choose each?

IntermediateDevelopment

CONCEPT ANSWER List: ordered, allows duplicates, index-based access. Use for sequential processing, DML operations (DML requires List), maintaining order, or iterating results. Set: unordered, unique elements, no index. Use for collecting unique Ids before SOQL, checking membership with contains(): O(1), or deduplicating values. Map: key-value pairs, unique keys, O(1) lookup by key. Use whenever you need to find a record by Id inside a loop: the most critical performance pattern in Salesforce.

111

What is the difference between shallow copy and deep copy for Apex collections? Why does it matter?

IntermediateDevelopment

BEST PRACTICE ANSWER Shallow copy copies the reference: both variables point to the same object in memory. Changing one changes the other. Deep copy creates a new independent copy. Changing the copy does not affect the original. In Apex, List<String> copy = original is a shallow copy: same list object. new List<String>(original) creates a new list with the same elements: a deep copy for primitives. For SObjects, even new List<Account>(original) gives a new list but the Account objects inside still share references.

113

What is the best way to remove duplicates from a List of custom objects in Apex?

AdvancedDevelopment

BEST PRACTICE ANSWER Removing duplicates from a List<String> or List<Id> is simple: add to a Set which auto-deduplicates, then convert back to List. For List<SObject> or custom objects it is more complex because Sets use reference equality for objects: two different Account instances with the same Id are not considered equal by a Set. Approach 1 for SObjects: use a Map<Id,SObject>. Iterating the list and putting each record into the map by Id automatically deduplicates: later entries overwrite earlier ones with the same key. Then call map.values() for the deduplicated List.

114

What are the best practices for writing Apex test classes?

IntermediateDevelopment

CONCEPT ANSWER 1. Use @testSetup for shared test data: data inserted in @testSetup is rolled back after all tests in the class run, not after each test, so it is created once and available to all test methods. 2. Test bulk behavior: always test with 200 records, not just 1. Triggers and service classes must work for bulk operations. 3. Assert specific values: do not just assert that no exception was thrown. Assert exact field values, record counts, and state changes. 4.

115

What is the difference between unit tests and integration tests in Apex? How do you write true unit tests?

AdvancedDevelopment

BEST PRACTICE ANSWER Integration tests test the full stack: trigger fires, handler runs, service is called, DML executes, related records update. Most Salesforce test classes are integration tests; they insert real data and rely on the full chain executing. Unit tests test one method or class in complete isolation: all dependencies are replaced with mocks or stubs. The method under test is the only real code running. True Apex unit tests: use Stub API (Test.createStub) or dependency injection to replace real SOQL calls, DML operations, and external callouts with controlled fakes.

116

Your test class has 75% code coverage but your deployment fails saying you need 75% overall org coverage. What could be wrong?

IntermediateDevelopment

The 75% requirement is not per-class; it is the aggregate coverage across ALL Apex classes and triggers in the org. Your individual test might cover 75% of its target class, but other classes in the org with low or zero coverage pull the overall percentage below 75%. Step 1: check the Apex Test Results in Setup to see which classes have the lowest coverage. Zero-coverage classes are the biggest problem. Step 2: check for classes that cannot be covered; inner classes, abstract base classes, or deprecated code. These still count in the denominator.

117

How do you test a method that calls an external API AND performs DML AND sends an email in the same transaction?

AdvancedDevelopment

This test has three dependencies to mock: HTTP callout, DML (database), and email sending. Each needs a different approach. Callout: use Test.setMock(HttpCalloutMock.class, new MockCallout()) before Test.startTest(). The mock responds with controlled data. DML: DML in tests is real; it executes against the test database which is rolled back after each test. We just need to create test data in @testSetup or directly in the test method. Email: wrap the email sending in a check for Test.isRunningTest(): if true, skip actual email dispatch and log to a list instead.

118

What is System.runAs() in Apex tests and when must you use it?

AdvancedDevelopment

BEST PRACTICE ANSWER System.runAs() executes a block of test code as a specified user, enforcing that user's permissions, profile, role, and sharing settings. By default test methods run as the running test user, usually a System Admin, which bypasses all permission and sharing checks. This means tests pass for admins but fail for regular users in production. Use System.runAs() for: testing with sharing enforcement; verifying that a user in a specific role sees only their records. Testing permission-based UI: a button that should only show for users with a custom permission.

119

What are the four types of async Apex? Give a one-line use case for each?

IntermediateDevelopment

CONCEPT ANSWER @future method: simplest async. Use for single callouts from triggers or mixed DML operations. Limitation: cannot chain, cannot monitor, only accepts primitives. Queueable interface: powerful async with job Id for monitoring. Use for sequential async processing, chaining jobs, passing SObjects, or callouts with complex data. Supports Database.AllowsCallouts. Batch Apex: for processing large volumes of records; up to 50 million. Divided into scope-sized chunks. Use for data migration, mass updates, scheduled cleanup, or any process that exceeds transaction limits.

120

A scheduled batch job runs at 2 AM and processes 50,000 records. Recently it started failing with UNABLE_TO_LOCK_ROW errors. What is happening and how do you fix it?

AdvancedDevelopment

UNABLE_TO_LOCK_ROW means a DML operation is trying to update a record that another transaction already has locked. At 2 AM if another process is also running, another batch, a trigger, a user saving a record, or another scheduled job, they compete for the same records. Fix 1: stagger job schedules. If multiple batch jobs run at the same time and touch the same objects, offset their start times by 15-30 minutes. Fix 2: reduce batch scope size. Smaller batches lock fewer records at a time, reducing the window of contention. Change from executeBatch(job, 200) to executeBatch(job, 50).

Integration

121

What are the main integration patterns in Salesforce?

BeginnerIntegration

Request-Reply (real-time sync), Fire-and-Forget (async), Batch Data Sync, and Remote Call-In. Choose based on data volume, timing, and reliability needs. Each pattern has specific implementation approaches.

122

What is REST API in Salesforce?

BeginnerIntegration

REST API provides a simple way to interact with Salesforce data over HTTP. It uses JSON or XML. It supports CRUD operations on records. It's the most commonly used API for integrations.

123

What is connected app?

BeginnerIntegration

A connected app configures how an external application integrates with Salesforce. It handles OAuth authentication. It defines permissions and access policies. It's required for API integrations.

124

What is middleware and why is it used?

BeginnerIntegration

Middleware sits between Salesforce and external systems to handle data transformation, routing, and error handling. Tools like MuleSoft, Dell Boomi, and Informatica are common. It simplifies complex integrations.

125

What is Salesforce Connect?

BeginnerIntegration

Salesforce Connect accesses external data in real-time without copying it into Salesforce. It uses External Objects and OData adapters. It's ideal for large datasets that change frequently.

126

What is the difference between inbound and outbound integration?

IntermediateIntegration

Inbound: external systems push data into Salesforce. Outbound: Salesforce sends data to external systems. Both use APIs, webhooks, or middleware. The direction determines the pattern and tools used.

127

How do you handle authentication in integrations?

IntermediateIntegration

OAuth 2.0 is the standard for API authentication. Named Credentials store credentials securely. JWT Bearer flow works for server-to-server. Session-based auth is used for UI integrations.

128

What is Change Data Capture?

IntermediateIntegration

CDC publishes real-time change events when records are created, updated, deleted, or undeleted. External systems can subscribe to these events. It's efficient for near real-time data sync.

129

How do you handle error handling in integrations?

IntermediateIntegration

Implement retry logic for transient failures. Log errors to custom objects. Use dead letter queues for failed messages. Set up monitoring and alerts. Design idempotent operations.

130

What is the Bulk API and when do you use it?

IntermediateIntegration

Bulk API processes large data sets asynchronously. It's optimized for loading or deleting thousands to millions of records. Use it when Data Loader or REST API can't handle the volume.

131

How do you design an enterprise integration architecture?

AdvancedIntegration

Define integration patterns per use case. Use an API-led approach with system, process, and experience layers. Implement centralized error handling and monitoring. Document data mappings and SLAs.

132

What is MuleSoft and how does it integrate with Salesforce?

AdvancedIntegration

MuleSoft is Salesforce's integration platform. It provides Anypoint Platform for building APIs. It has native Salesforce connectors. It enables API-led connectivity across systems.

133

How do you handle real-time vs near-real-time integration?

AdvancedIntegration

Real-time uses synchronous APIs or Platform Events. Near-real-time uses CDC or outbound messages. Consider latency, volume, and reliability requirements. Real-time has tighter governor limits.

134

An integration is intermittently failing. How do you investigate?

AdvancedIntegration

Check debug logs for error details. Review the integration user's API usage. Verify endpoint availability and response times. Check for governor limit violations. Implement retry logic and error logging if not already in place.

135

You need to sync data bidirectionally between Salesforce and an ERP system. How?

AdvancedIntegration

Define the system of record for each field. Use Change Data Capture or Platform Events for real-time sync. Implement conflict resolution logic. Use external IDs for record matching. Consider middleware like MuleSoft for transformation and orchestration.

136

How do you make a REST API callout from Apex?

IntermediateIntegration

[BASIC] ANSWER We use the HttpRequest, Http, and HttpResponse classes in Apex. First we create an HttpRequest object and set the endpoint, method (GET/POST), headers, and body. Then we create an Http object and call send() passing the request. This returns an HttpResponse with the status code and body. In our Razorpay integration we set the endpoint using Named Credential syntax as callout:Razorpay/v1/orders, set method as POST, set Content-Type header as application/json, serialize our request object as JSON and set it as the body.

137

What is the difference between GET and POST in REST API?

IntermediateIntegration

[BASIC] ANSWER GET is used to retrieve or fetch data from an external system. It does not have a request body: parameters are passed in the URL itself. For example, fetching order status from Razorpay by passing order ID in the URL. POST is used to create or send data to an external system. It has a request body where we send JSON or XML data. For example, creating a new payment order in Razorpay; we send amount, currency, and receipt in the POST body. In our Razorpay integration we use POST to create the order because we are sending data to Razorpay to create a new record on their system.

138

How do you parse a JSON response in Apex?

IntermediateIntegration

[BASIC] ANSWER There are two ways to parse JSON in Apex. First way is using JSON.deserializeUntyped(); this gives us a Map of String to Object. We then cast individual values to the expected type like String or Integer. This is flexible but requires manual casting. Second way is using JSON.deserialize() with a specific Apex wrapper class; we define a class with matching field names and Salesforce automatically maps the JSON fields to class properties. This is cleaner and type-safe.

139

Can you make a callout directly from a trigger? Why or why not?

IntermediateIntegration

No, we cannot make a direct callout from a trigger. Salesforce does not allow synchronous callouts from triggers because triggers run inside a database transaction. If the callout is made synchronously, the database transaction would be held open waiting for the external system to respond; this can cause lock issues and timeouts. The solution is to use an @future method with callout=true annotation, or a Queueable class that implements the Database.AllowsCallouts interface. These run asynchronously after the transaction is committed.

140

What is callout timeout and how do you handle it?

IntermediateIntegration

Callout timeout is the maximum time Salesforce waits for a response from an external system. The default timeout is 10 seconds and the maximum allowed is 120 seconds. We set it using req.setTimeout() in milliseconds. If the external system does not respond within the timeout, Salesforce throws a CalloutException with a timeout message. To handle this properly, we wrap our callout in a try-catch block catching CalloutException specifically. In the catch block we log the error, update the record with a failure status, and optionally retry using a Queueable job.

141

What is the maximum number of callouts allowed in a single transaction and how do you handle bulk scenarios?

AdvancedIntegration

Salesforce allows a maximum of 100 callouts per transaction; this is a governor limit. Each call to http.send() counts as one callout. In bulk scenarios, for example if 200 Opportunities are closed won at the same time, we cannot make 200 callouts in one transaction. The solution is to use @future methods which run per record, or better a Queueable chain where each job processes one record and chains the next job. There is also a daily limit of 250,000 callouts per org.

142

What is an @future method and when do you use it?

AdvancedIntegration

[BASIC] ANSWER An @future method is an asynchronous Apex method that runs in a separate thread after the current transaction is committed. We annotate it with @future and it must be static and return void. We use @future in three main scenarios: first, when we need to make a callout from a trigger (we add callout=true to the annotation). Second, when we need to avoid mixed DML operations. Third, when we want to offload heavy processing so it does not slow down the current transaction. The limitations of @future are that it cannot take SObject as a parameter, only primitive types.

143

Why can @future methods not accept SObject parameters?

AdvancedIntegration

[BASIC] ANSWER @future methods run asynchronously in a separate transaction that executes later. If we passed an SObject directly, by the time the @future method runs, the SObject data in memory could be stale or different from what is actually in the database. To avoid this inconsistency, Salesforce restricts @future parameters to primitives only, like String, Integer, Id, or collections of primitives like List of Id. The correct pattern is to pass the record Id as a parameter and then re-query the latest data inside the @future method itself.

144

What is the difference between @future, Queueable, and Batch Apex? When would you use each?

IntermediateIntegration

@future is the simplest: fire and forget. Use it for quick async operations like single callouts from triggers or mixed DML fixes. Limitation is you cannot chain jobs or monitor them. Queueable is more powerful than @future. It can accept SObject parameters, can be chained: meaning one Queueable can enqueue another, and you get a job ID to monitor. Also supports callouts with Database.AllowsCallouts interface. Batch Apex is for processing large volumes of records: up to 50 million records. It processes records in chunks called scope.

145

How do you test @future methods in test classes?

IntermediateIntegration

@future methods do not execute during a test until we call Test.stopTest(). This is because they are asynchronous: Salesforce holds them in a queue. The correct pattern is to set up test data, call Test.startTest() which resets governor limits, perform the action that triggers the @future method, then call Test.stopTest(). When Test.stopTest() is called, Salesforce executes all queued async operations synchronously before returning. We also need to use Test.setMock() with HttpCalloutMock before the Test.startTest() block to mock the external API response.

146

What happens if an @future method fails? How do you handle retries?

AdvancedIntegration

If an @future method throws an unhandled exception, Salesforce marks the job as failed and it does not retry automatically. The failure is logged in Apex Jobs in Setup but no notification is sent to users. To handle failures properly we should always wrap the entire @future method body in a try-catch block. In the catch block we should log the error to a custom Error Log object, update the record with a failure status, and optionally send an email notification to an admin.

147

Can you explain what OAuth 2.0 is and how it works?

AdvancedIntegration

[BASIC] ANSWER OAuth 2.0 is an authorization framework that allows an application to access resources on behalf of a user without sharing the user's password. Instead of credentials, it uses tokens. The basic flow: our application first requests an access token from the authorization server by providing a Client ID and Client Secret. The authorization server validates these and returns an access token with an expiry time. We then use this access token in the Authorization header of every API request as a Bearer token. When the token expires we request a new one using a refresh token.

148

How do you configure OAuth 2.0 in Salesforce using Named Credentials?

IntermediateIntegration

To configure OAuth 2.0 in Salesforce we need three things: an Auth Provider, an External Credential, and a Named Credential. First we create an Auth Provider in Setup. We select the provider type, for example Custom for PayPal. We enter the Client ID, Client Secret, and the token endpoint URL. Salesforce uses this to fetch and refresh access tokens. Second we create an External Credential and set the Authentication Protocol to OAuth 2.0. We link it to the Auth Provider. We also add a Principal and map it to the appropriate Permission Set.

149

What is the difference between Client Credentials flow and Authorization Code flow?

IntermediateIntegration

Client Credentials flow is for machine-to-machine communication where no user is involved. The application authenticates directly using its own Client ID and Secret. There is no login screen or user consent step. This is used for server-side integrations like our Salesforce to PayPal integration. Authorization Code flow is for user-facing applications where the actual user needs to authenticate and grant permission. The user is redirected to the external system's login page, they log in and approve access, and then the application exchanges an authorization code for an access token.

150

What happens when an OAuth access token expires during a callout? How does Salesforce handle it?

AdvancedIntegration

When an OAuth access token expires, the external system returns a 401 Unauthorized response. If we are using Named Credentials with an Auth Provider, Salesforce handles this automatically. When it receives a 401, it uses the refresh token to request a new access token, then retries the original callout with the new token: completely transparent to our Apex code. However if we are managing tokens manually in Apex, storing them in Custom Settings or Custom Metadata, we need to handle expiry ourselves.

151

What is HttpCalloutMock and why do we need it in test classes?

AdvancedIntegration

[BASIC] ANSWER HttpCalloutMock is an interface in Salesforce that we implement to simulate HTTP callout responses in test classes. Salesforce does not allow actual HTTP callouts during test execution: if we try to make a real callout in a test, it throws an exception. We create a class that implements HttpCalloutMock and override the respond() method. In this method we construct and return a fake HttpResponse with the status code and body we want to simulate. Then in our test method we call Test.setMock() to register our mock class before executing the callout code.

153

How do you handle errors in Apex callouts? What are best practices?

IntermediateIntegration

There are multiple types of errors we need to handle in callouts. First, network or system errors; we catch CalloutException for timeouts and connection failures. Second, HTTP error responses; we check the status code. 200 means success. 400 means bad request. 401 means unauthorized. 404 means not found. 500 means external system error. Third, JSON parsing errors: if the response body is not valid JSON, JSON.deserializeUntyped() throws an exception, so we wrap parsing in a try-catch too. Best practices: always use try-catch with specific exception types.

154

What is the difference between CalloutException and System.Exception?

IntermediateIntegration

CalloutException is a specific exception thrown by Salesforce when there is a network-level problem with the callout itself: things like timeout, connection refused, SSL handshake failure, or the callout limit being exceeded. It means the request never got a proper response from the server. System.Exception or generic Exception catches everything else, like null pointer errors, JSON parsing failures, type cast errors, or any other unexpected runtime error in our code.

155

How would you design a retry mechanism for failed callouts in Salesforce?

AdvancedIntegration

A retry mechanism needs to be asynchronous because we cannot do a synchronous loop of retries inside a transaction; we would hit timeout limits. The best design uses a Queueable chain with a retry count. We create a Queueable class that accepts the record Id and a retry count. Inside execute() we attempt the callout. If it fails and retry count is less than max retries, say 3, we enqueue a new instance of the same Queueable with retry count plus one. We also need a custom field on the record to track retry count and last error for monitoring.

LWC

156

What is Lightning Web Components (LWC)?

BeginnerLWC

LWC is Salesforce's modern component framework built on web standards. It uses native JavaScript, HTML templates, and CSS. It's faster than Aura components. It's the recommended framework for new Salesforce UI development.

157

What is the difference between Aura and LWC?

BeginnerLWC

LWC uses native web standards while Aura uses a custom framework. LWC is more performant. Aura has more lifecycle events. LWC can be used inside Aura but not vice versa. New development should use LWC.

158

What is the Lightning App Builder?

BeginnerLWC

A drag-and-drop tool for building Lightning pages. Admins can customize record pages, home pages, and app pages. It supports standard and custom components. No coding required.

159

What are Lightning record pages?

BeginnerLWC

Custom page layouts built in Lightning App Builder. They can contain standard and custom components. They're assigned by app, record type, or profile. They replace Visualforce page overrides.

160

What is the wire service in LWC?

IntermediateLWC

The wire service reactively provisions data to LWC components. It connects to Salesforce data via wire adapters. It automatically refreshes when data changes. It's the recommended way to read data in LWC.

161

How do you communicate between LWC components?

IntermediateLWC

Parent to child: use public properties (@api). Child to parent: use custom events. Unrelated components: use Lightning Message Service (LMS) or pub-sub pattern.

162

What is Lightning Data Service?

IntermediateLWC

LDS provides a centralized data cache for Lightning components. It handles CRUD operations without Apex. It ensures data consistency across components. It respects sharing and FLS automatically.

163

How do you handle navigation in Lightning?

IntermediateLWC

Use NavigationMixin to navigate between pages, records, and lists. It supports URL-based navigation too. It replaces force:navigateToSObject from Aura. It works with standard and custom pages.

164

What is Lightning Message Service?

IntermediateLWC

LMS enables communication between LWC, Aura, and Visualforce components on the same page. It uses message channels defined in metadata. It's the recommended cross-technology communication method.

165

How do you make LWC components reusable?

AdvancedLWC

Use @api properties for configuration. Design components with single responsibility. Create base components that others extend. Use slots for content projection. Document the component API.

166

What are Lightning Web Security and Locker Service?

AdvancedLWC

Security frameworks that isolate components in namespaces. LWS is the newer, more permissive replacement for Locker. They prevent components from accessing each other's DOM. They enforce secure coding practices.

167

How do you optimize LWC performance?

AdvancedLWC

Minimize wire calls and Apex invocations. Use lazy loading for heavy components. Cache data client-side when appropriate. Avoid unnecessary re-renders. Use if:true directives to conditionally render.

168

What are the lifecycle hooks in LWC and in what order do they execute?

IntermediateLWC

LWC has five main lifecycle hooks that execute in a specific order. constructor() fires first when the component is created. At this point the component is not yet in the DOM and we cannot access child elements. We use it for initializing variables. connectedCallback() fires when the component is inserted into the DOM. This is where we typically do setup work like subscribing to message channels or fetching initial data that does not need reactive properties. renderedCallback() fires after every render of the component: both the initial render and every subsequent re-render.

169

What is the difference between @api, @track, and @wire decorators?

IntermediateLWC

These three decorators serve completely different purposes in LWC. @api marks a property or method as public; it can be set by a parent component or accessed externally. If a parent passes a value to a child, the child's receiving property must be decorated with @api. Objects and arrays decorated with @api are read-only inside the component; you cannot mutate them directly. @track marks a property for deep reactivity. In modern LWC (API 39+), primitive properties are already reactive by default: the component re-renders when they change.

170

What is Shadow DOM in LWC and why does it matter?

IntermediateLWC

Shadow DOM is a web standard that provides encapsulation for a component's HTML, CSS, and JavaScript. In LWC, every component has its own shadow root: meaning the component's internal DOM is hidden from the outside world. This matters for three reasons. First, CSS encapsulation: styles defined inside a component do not leak out to the parent, and parent styles cannot bleed into the child. This prevents unintentional style conflicts. Second, DOM isolation: external JavaScript cannot directly query elements inside a component using document.querySelector.

171

What is the difference between LWC and Aura components? Why did Salesforce move to LWC?

AdvancedLWC

LWC and Aura are two different component frameworks on the Salesforce platform. Aura was the original framework, and LWC is the modern replacement introduced in 2019. The key technical differences are: LWC is built on modern web standards like Web Components, Shadow DOM, and ES6+ modules. Aura was a proprietary framework with its own abstractions that added overhead. LWC is significantly faster because it compiles to native browser APIs, whereas Aura had a heavy JavaScript framework layer. In LWC we use standard JavaScript classes and decorators.

172

What is a getter in LWC and when do you use it instead of a tracked property?

AdvancedLWC

A getter is a JavaScript class accessor that computes a value derived from other properties. In LWC we use getters frequently in templates as dynamic computed values. We use getters instead of tracked properties when a value is always computed from other state rather than stored independently. For example: a fullName getter that combines firstName and lastName, a CSS class getter that returns different classes based on a status property, or a formatted currency getter.

173

How does data binding work in LWC? What is the difference between one-way and two-way binding?

AdvancedLWC

LWC uses one-way data binding by default: data flows down from parent to child through properties, and events flow up from child to parent. This is the unidirectional data flow pattern. In templates we use curly braces for one-way binding: value={myProperty}. When myProperty changes, the template re-renders. But changes in the template input do not automatically update myProperty; we need an event handler like onchange to capture the change and update the property manually. There is no automatic two-way binding in LWC like Angular's ngModel or older frameworks.

174

How does parent-to-child communication work in LWC?

IntermediateLWC

Parent-to-child communication in LWC happens through public properties and public methods. For properties: the child component exposes a property with the @api decorator. The parent sets this property directly in the HTML template as an attribute. When the parent updates the value, the child automatically re-renders with the new value. For methods: the child exposes a method with the @api decorator. The parent gets a reference to the child using the template.querySelector selector and then calls the method directly.

175

How does child-to-parent communication work in LWC?

IntermediateLWC

Child-to-parent communication in LWC is done using CustomEvents. The child dispatches a custom event and the parent listens to it. In the child component we create a CustomEvent object with an event name and optionally a detail payload. We dispatch it using this.dispatchEvent(). If we need the event to cross shadow boundaries and reach grandparent components, we set bubbles true and composed true. In the parent template we listen to the event using the on prefix followed by the event name as an attribute.

176

How do you communicate between sibling components or unrelated components in LWC?

AdvancedLWC

Direct communication between sibling components is not possible in LWC. Siblings cannot talk to each other directly; there are two patterns to solve this. Pattern one is to use the parent as a mediator. The first sibling dispatches an event to the parent, the parent handles it and updates a property, then passes that updated property down to the second sibling via @api. This is the simplest pattern and works well when both siblings share a common parent. Pattern two is Lightning Message Service: LMS.

177

How do you handle a scenario where a deeply nested child needs to update data in a grandparent component?

AdvancedLWC

A deeply nested child communicating with a grandparent is a common architectural challenge in LWC. We have two clean patterns. Pattern one: event bubbling. The child dispatches a custom event with bubbles true and composed true. Each intermediate parent does not need to handle it: the event bubbles up automatically to the grandparent which has the listener. This is clean but can lead to unexpected event handling if intermediate components accidentally have the same event name. Pattern two: Lightning Message Service.

178

What is the Wire Service in LWC and how does it work?

IntermediateLWC

Wire Service is a reactive data provisioning mechanism in LWC. It automatically fetches data from a wire adapter and re-fetches it whenever the reactive parameters change, without us needing to write imperative callout code. Wire works with built-in Salesforce adapters like getRecord, getRelatedListRecords, getPicklistValues, and also with Apex methods annotated with @AuraEnabled(cacheable=true). We can wire data to either a property or a function. When wired to a property, the result has data and error attributes.

179

What is the difference between @wire and imperative Apex calls? When do you use each?

IntermediateLWC

Wire and imperative calls are two ways to call Apex from LWC and each has its use case. @wire is declarative and reactive. Salesforce automatically calls the Apex method when the component loads and re-calls it when parameters change. The Apex method must be cacheable=true. Use wire for read-only data that should load automatically, like displaying a record's details, loading a list on page load, or any data that refreshes when a record ID changes. Imperative calls are explicit; we call the imported Apex method like a regular JavaScript function inside an event handler or lifecycle hook.

180

How does Lightning Data Service (LDS) work in LWC and what are its advantages?

AdvancedLWC

Lightning Data Service is a client-side data layer that Salesforce provides for reading, creating, updating, and deleting records. It acts as a shared cache between components on the same Lightning page. LDS works through wire adapters like getRecord, getRecordCreateDefaults, and through the lightning-record-form, lightning-record-view-form, and lightning-record-edit-form base components which use LDS internally. The key advantages are: first, shared cache: if two components on the same page wire the same record, LDS serves both from a single cached copy.

181

What is refreshApex and when do you use it? What are its limitations?

AdvancedLWC

refreshApex is a function imported from salesforce/apex that forces a wired property to re-fetch its data from the server, bypassing the client-side cache. We use it after performing a DML operation imperatively. For example: if we have a wired list of contacts and the user adds a new contact through an imperative Apex call, the wire cache still holds the old list. Calling refreshApex on the wired property forces it to go back to the server and get the updated list. To use refreshApex, we must wire data to a property and store the entire wire result, not just the data.

182

What is the difference between bubbles and composed in CustomEvent?

IntermediateLWC

bubbles and composed are two properties that control how a custom event travels through the DOM. bubbles controls whether the event travels up the DOM tree. When bubbles is false, the default, the event stays at the component that dispatched it and only the direct parent listening with an event handler on the child tag will receive it. When bubbles is true, the event travels up through ancestor components. composed controls whether the event crosses shadow DOM boundaries.

183

What is Lightning Message Service (LMS) and when do you use it?

IntermediateLWC

Lightning Message Service is Salesforce's publish-subscribe messaging system for communication between components that do not share a direct parent-child relationship on a Lightning page. We use LMS when: two components are in different regions of a Lightning record page, one is an LWC and the other is an Aura component or Visualforce, or they simply do not have a common parent component to mediate. LMS requires three things. First a Message Channel: a metadata file with .messageChannel-meta.xml extension that defines the channel.

184

What are the key differences between LMS and the older pubsub module?

AdvancedLWC

LMS is Salesforce's officially supported publish-subscribe solution, while pubsub was a community-built JavaScript module that developers imported manually as a utility. The key differences are: first, official support: LMS is built into the platform and officially maintained by Salesforce. pubsub was a community pattern with no official support or guarantee. Second, cross-framework: LMS works across LWC, Aura, and Visualforce on the same page. pubsub only worked between LWC components. Third, page scoping: LMS messages are scoped to the Lightning page context using MessageContext.

185

How do you implement navigation in LWC?

IntermediateLWC

Navigation in LWC is done using the NavigationMixin from lightning/navigation. We mix it into the component class using class syntax: extends NavigationMixin(LightningElement). The main method is this[NavigationMixin.Navigate](pageReference) which takes a PageReference object. A PageReference is a JSON object that describes a page type and its attributes.

186

How would you pass data between two unrelated LWC components during navigation?

AdvancedLWC

When navigating from one Lightning page to another, LMS cannot be used because it only works within the same page context. We have several patterns for passing data across navigation. Pattern one: URL state parameters. We can pass simple data as state in the PageReference object. The target page reads it using CurrentPageReference wire adapter. This works for simple primitive values like IDs or filter values. Pattern two: Record ID. We navigate to a record page passing the record ID. The target component uses the recordId @api property and wires getRecord to fetch everything it needs.

187

What is the difference between lightning-record-form, lightning-record-view-form, and lightning-record-edit-form?

AdvancedLWC

All three are LDS-based base components for working with Salesforce records, but they offer different levels of control. lightning-record-form is the simplest. It automatically renders fields in view or edit mode based on the layout-type or fields you pass. It handles everything: labels, values, edit/save/cancel buttons. Use it when you want a quick form with minimal customization. lightning-record-view-form gives more control over the display.

188

What are lazy loading and conditional rendering in LWC and how do they improve performance?

IntermediateLWC

Lazy loading means deferring the loading of data or components until they are actually needed: instead of loading everything upfront when the page first renders. In LWC we implement lazy loading by not calling Apex or wire in connectedCallback for data that is not immediately visible. Instead we trigger the load on user action, like clicking a tab, expanding a section, or scrolling to a part of the page. This reduces the initial load time and server requests.

189

How do you avoid infinite loops in renderedCallback? What are other common LWC performance pitfalls?

AdvancedLWC

renderedCallback fires after every render including re-renders triggered by state changes. If we change state inside renderedCallback it triggers another render which calls renderedCallback again: causing an infinite loop. The solution is to use a boolean flag: a private property like _isRendered. At the start of renderedCallback we check if _isRendered is true and return early. Otherwise we set it to true and do our work. This ensures the code inside runs only once after the first render.

190

What is the difference between this.template.querySelector and document.querySelector in LWC?

IntermediateLWC

this.template.querySelector searches for an element within the component's own shadow DOM; its own template. It respects shadow DOM encapsulation and is the correct way to access child elements inside a component. document.querySelector searches the entire document DOM including all shadow trees. In LWC, due to synthetic shadow DOM, this can sometimes work, but it is considered an anti-pattern because it breaks encapsulation, can accidentally select elements from other components, and may break in future Salesforce releases that move to native shadow DOM.

191

What are slots in LWC and how do you use them for component composition?

AdvancedLWC

Slots are placeholders in a child component's template where a parent can inject its own markup. They are a powerful pattern for building reusable container or layout components. A default slot, written as slot tag with no name, accepts any content the parent places inside the child component tags. A named slot has a name attribute and the parent targets it using the slot attribute on the injected element. Slots enable component composition: instead of duplicating layout code, we build a generic container component with slots and reuse it with different content in each usage.

192

What are the best practices for writing secure LWC components? What replaced Locker Service?

AdvancedLWC

Lightning Web Security (LWS) has replaced Locker Service as the security architecture that isolates JavaScript code running in Lightning components; Locker Service is the older version of the same idea. It prevents components from one namespace from accessing the DOM or JavaScript of components in another namespace. Under Locker Service, DOM access is restricted; we cannot use document.cookie, access native DOM APIs directly in some cases, or manipulate elements outside our component's shadow. This protects against XSS attacks and malicious third-party components.

Scenario-Based

193

Design a Salesforce–Payment Gateway Integration from Scratch?

IntermediateScenario-Based

When an Opportunity is marked Closed Won, a payment order should be created automatically and the payment link stored on the record. How would you design this end-to-end? MODEL ANSWER I would design this in four layers: trigger, handler, callout service, and LWC display. Layer 1: Trigger: I would create an after-update trigger on Opportunity. Direct callouts from triggers are not allowed, so the trigger would call a handler class. Layer 2: Trigger Handler: The handler checks if StageName changed to Closed Won and if a payment order does not already exist.

194

Callout is Failing with 401 Unauthorized: How Do You Debug?

IntermediateScenario-Based

The same code was working fine in sandbox. What steps would you take to debug and fix this? MODEL ANSWER A 401 in production but not sandbox almost always means a credentials or authentication configuration issue. Step 1: Check Named Credentials / External Credentials. The sandbox and production have separate Named Credentials. When we deploy code, the Named Credential metadata deploys but the actual credential values, API keys, secrets, tokens, do NOT migrate. Someone needs to manually enter the credentials in production.

195

@future vs Queueable; Which to Use for Callouts?

IntermediateScenario-Based

A junior developer suggests using @future methods. Would you agree? What would you recommend? MODEL ANSWER I would not fully agree with @future for this scenario. Let me explain the trade-offs. @future works fine for a single callout per record. But for a batch of records with multiple callouts each, @future has serious limitations; you cannot chain @future calls, cannot monitor them, cannot pass complex data, and each @future is a separate async job with no guaranteed order. For this scenario I would recommend Queueable with Database.AllowsCallouts for the following reasons.

196

@future Method Not Updating the Record?

IntermediateScenario-Based

In testing they find the Opportunity fields are not being updated after the callout. The debug log shows the update DML ran. What could be wrong? MODEL ANSWER There are three common causes for this scenario. Cause 1: The @future method is querying stale data. If the Opportunity was modified after the @future was enqueued but before it ran, the method might be querying an old version. However since the update DML is running, this alone would not explain why fields are not saved: unless there is a validation rule or trigger rolling it back.

197

Handling API Rate Limits from External System?

IntermediateScenario-Based

Interviewer: The external payment gateway you are integrating with has a rate limit of 100 requests per minute. Your Salesforce org processes up to 500 Opportunities per hour during peak time. How do you handle this? MODEL ANSWER This is a rate limiting design problem. Firing all callouts immediately would exceed the gateway's limit and cause 429 Too Many Requests errors. Solution 1: Queueable with delay. We use a Queueable chain that processes one record at a time with a controlled pace.

198

Design Bidirectional Sync Between Salesforce and External CRM?

IntermediateScenario-Based

Contact records must stay in sync: changes in Salesforce push to the external CRM, and changes in the external CRM must update Salesforce. How do you design this bidirectional sync without creating infinite loops? MODEL ANSWER Bidirectional sync is complex and the biggest risk is sync loops: Salesforce updates external CRM, external CRM calls back to Salesforce, Salesforce triggers again and updates external CRM again, infinitely. The key design principle is: each system must mark records it owns to avoid re-processing its own updates.

199

Callout Limit Exception in Bulk Trigger?

IntermediateScenario-Based

It happens when a large data import updates many Opportunities at once. How do you fix this? MODEL ANSWER This error means more than 100 http.send() calls happened in a single transaction: the governor limit. In a bulk trigger scenario, if we make a callout per record inside the trigger's loop, 101 records will exceed the limit. The root cause is that the integration was designed for single-record updates and not bulk-safe. Fix 1: Move callouts out of the trigger entirely. Replace the synchronous callout with an @future or Queueable call per record.

200

Named Credentials vs Hardcoded Endpoint: Making the Case?

IntermediateScenario-Based

It's simpler.' How do you respond? MODEL ANSWER I would respectfully disagree and explain why Named Credentials are worth the setup. Security: Hardcoding in Custom Settings stores credentials in plaintext that any admin or developer with access to Custom Settings can see. Named Credentials store credentials encrypted on the platform with no way to retrieve the raw value. Audit and Compliance: In environments with compliance requirements like PCI-DSS or SOC2, credentials must be stored securely. Named Credentials satisfy this requirement. Custom Settings do not.

201

External API Returns Inconsistent JSON Structure?

IntermediateScenario-Based

Interviewer: The external API you are calling sometimes returns a flat JSON object and sometimes wraps the data in a nested results key depending on whether it found one record or multiple. How do you handle this in Apex? MODEL ANSWER This is a classic inconsistent API response problem and requires defensive parsing. First I would document the two response shapes and write the parser to handle both cases. The approach is: after deserializing the response to a Map<String,Object>, I first check if the results key exists.

202

Design a Retry Mechanism for Failed Payment Callouts?

IntermediateScenario-Based

Business requires that failed payments are retried up to 3 times before being marked as permanently failed. How do you design this? MODEL ANSWER I would design this using a Queueable chain with exponential backoff: a well-established retry pattern. Step 1: Custom fields on Opportunity: Razorpay_Retry_Count__c (Number), Razorpay_Last_Error__c (Text), Razorpay_Order_Status__c (Text). Step 2: Queueable class accepts oppId and retryCount. Inside execute(), it makes the callout. On success, it updates the Opportunity with the order details and sets status to Created.

203

How Do You Secure Inbound API Calls to Salesforce?

IntermediateScenario-Based

Interviewer: An external system needs to call Salesforce to push data. You expose a custom Apex REST endpoint. The external team asks how the endpoint is secured so no unauthorized system can call it. What do you tell them? MODEL ANSWER Salesforce Apex REST endpoints are not publicly accessible by default; they require authentication. Here is how we secure them. Option 1: OAuth 2.0 Connected App: We create a Connected App in Salesforce and configure OAuth 2.0.

204

Choosing Between Platform Events and @future for Async Processing?

IntermediateScenario-Based

Another says @future is simpler. For a scenario where 50 records need callouts when updated, which would you choose and why? MODEL ANSWER Both are valid but for different scenarios. Let me compare them for this specific case. @future approach: Simple to implement, works well for low volume. Each record update fires an @future. Works fine for 50 records if they do not all update simultaneously. Limitations: no visibility into queue, no retry built in, order not guaranteed. Platform Events approach: The trigger publishes a Platform Event per record.

205

Test Class Failing with CalloutException: Callouts Not Permitted?

IntermediateScenario-Based

The test is failing with 'System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.' What is wrong? MODEL ANSWER This error means there is a DML operation, insert, update, delete, that happened before the callout attempt in the same test context without being committed or rolled back. Salesforce does not allow callouts after uncommitted DML in the same transaction. This is a real platform restriction, not just a test issue.

206

Design a Product Selector LWC with Parent-Child Communication?

IntermediateScenario-Based

When the user selects a product, a child component shows the product details and the price updates in real time. How would you architect this? MODEL ANSWER I would build this with three components: a product-list parent, a product-card child for each product, and a product-detail child for the selected product details. Component 1: product-list (parent): Wires getProducts Apex method to load the product list. Renders a list of product-card components passing each product as @api prop. Listens to a productselect event from product-card.

207

LWC Component Not Re-rendering After Data Change?

IntermediateScenario-Based

After the user clicks a button that calls an Apex method to insert a new record, the list does not update to show the new record. What is wrong and how do you fix it? MODEL ANSWER This is a very common issue: the wire cache is stale after an imperative DML operation. Root cause: @wire with cacheable=true Apex methods use a client-side cache. When the imperative insert runs, it adds a record to the database but the wire cache is not automatically invalidated. The component still shows data from the old cache.

208

CSS Styles Not Applying to Child Component?

IntermediateScenario-Based

The developer is confused. What is the problem and what is the fix? MODEL ANSWER The problem is Shadow DOM CSS encapsulation. In LWC, every component has its own shadow root. CSS styles defined in the parent component's CSS file cannot pierce into the child component's shadow DOM. This is intentional and a feature; it prevents style pollution between components. But it means the parent cannot directly style the internals of a child. There are two correct solutions. Solution 1: CSS Custom Properties (CSS Variables): The parent sets a CSS custom property on the child component's host element.

209

Show Different UI Based on User's Profile or Permission?

IntermediateScenario-Based

Interviewer: You need to show a Delete button in an LWC component only to System Administrators and users with a specific custom permission. How do you implement this? MODEL ANSWER There are two ways to check this in LWC, custom permissions and user data, and I would combine both. For custom permissions: Salesforce provides @salesforce/customPermission imports in LWC. We import the custom permission using import hasDeletePermission from '@salesforce/customPermission/Delete_Payment_Records'. This returns a boolean at runtime based on whether the current user has the permission assigned.

210

When to Use LMS vs CustomEvent for Component Communication?

IntermediateScenario-Based

Component A is in the left sidebar, Component B is in the main content area. They are not related parent-child. When user selects something in A, B should update. Do you use CustomEvents or LMS? MODEL ANSWER For this scenario I would use LMS, Lightning Message Service, and here is exactly why. CustomEvents with bubbles and composed true travel up the DOM tree. But Component A and Component B are in different regions of the Lightning page; they are rendered in completely separate DOM trees that do not share a common parent within our control.

211

Infinite Loop in renderedCallback Crashing the Browser?

IntermediateScenario-Based

The browser tab keeps crashing and the console shows renderedCallback being called thousands of times. How do you fix this? MODEL ANSWER This is the classic renderedCallback infinite loop. Here is exactly what is happening and how to fix it. The root cause: inside renderedCallback, the developer is probably setting a tracked property or calling a method that changes component state. Any state change in LWC triggers a re-render. A re-render calls renderedCallback again. This creates an infinite loop. The fix is the _isRendered boolean guard pattern.

212

Design an LWC Form with Validation, Save, and Cancel?

IntermediateScenario-Based

It must validate that First Name, Last Name, and Email are filled, show inline validation errors, save via Apex, show a success toast, and reset the form on Cancel. How do you build this? MODEL ANSWER I would build this as a self-contained LWC component with clear state management. Template structure: three lightning-input fields for First Name, Last Name, Email. Each input has value={contact.firstName} and onchange={handleFieldChange} with a data-field attribute to identify which field changed. Below each input, a conditional error message using if:true={errors.firstName}.

213

LWC on a Record Page Needs to Refresh After Another Component Saves?

IntermediateScenario-Based

Interviewer: You have two LWC components on the same Opportunity record page. Component A is a form that saves data. Component B displays a summary that includes the saved data. After Component A saves, how do you make Component B refresh automatically? MODEL ANSWER This is a cross-component refresh scenario and there are three clean solutions. Solution 1: LMS: Component A publishes an LMS message after a successful save. Component B subscribes to the channel. When B receives the message, it calls refreshApex on its wired data.

214

Handling Apex Errors Gracefully in LWC: Best Practices?

IntermediateScenario-Based

A junior developer is just console.logging the error. What improvements would you suggest? MODEL ANSWER Console.log is fine for debugging but terrible for user experience and production support. Here is the complete best practice. First: understand the error structure. Apex errors returned from LWC wire or imperative calls have a body property. body.message contains the user-friendly message. body.stackTrace has the stack trace. For AuraHandledException thrown in Apex, body.message is what we set in the constructor. Second: display user-friendly errors in the UI.

215

Build a Searchable Data Table with Pagination in LWC?

IntermediateScenario-Based

The list has 10,000 contacts. How do you design this for performance? MODEL ANSWER With 10,000 records, client-side operations are not an option. All filtering, sorting, and pagination must happen on the server side. Architecture: The LWC component maintains state for searchTerm, sortField, sortDirection, pageNumber, and pageSize. Whenever any of these change, an imperative Apex call is made with all parameters. The Apex method does a dynamic SOQL query with WHERE, ORDER BY, LIMIT, and OFFSET.

216

How Do You Navigate to a New Record After Saving in LWC?

IntermediateScenario-Based

Interviewer: After a user fills out a form and clicks Save, the record is created. You need to automatically navigate to the newly created record's detail page. How do you implement this? MODEL ANSWER This is a very practical pattern: create record then navigate to it. Step 1: Import NavigationMixin and extend the class with it. This adds the navigate method to the component. Step 2: The save button calls an imperative Apex method that returns the Id of the newly created record. The Apex method must return the Id explicitly, not just void.

217

Should You Use lightning-record-edit-form or Custom Apex for a Complex Save Operation?

IntermediateScenario-Based

Should you use lightning-record-edit-form or a custom Apex method? Justify your choice. MODEL ANSWER For this scenario I would use a custom Apex method called imperatively, not lightning-record-edit-form. Here is why. lightning-record-edit-form uses LDS under the hood. It can only save the single record's fields. It cannot execute custom business logic like sending emails or updating related records in the same transaction. The requirement has three operations, save Contact, send email, update Account counter, that must happen atomically.

Salesforce interview FAQ

01

How do I prepare for a Salesforce interview?

Start with the questions for your role and experience level on this page, and answer them out loud rather than just reading. Then practise scenario questions based on your own projects, because most interviews after the first round are about what you have built. Finish with a timed mock interview to check your weak areas.

02

What are the most important Salesforce interview topics in 2026?

For admins: security and sharing, Flow, and data management. For developers: Apex triggers, SOQL, governor limits, asynchronous Apex, LWC and integration. For everyone: Agentforce and Data 360 basics, because interviewers now ask about them in most roles.

03

How many questions should I practise before an interview?

Quality matters more than quantity. Practise 50 to 100 questions for your role until you can explain each one with an example from your work, then 10 to 20 scenario questions. That is more useful than reading 1,000 answers once.

04

Are Salesforce interview questions different for freshers and experienced candidates?

Yes. Freshers are asked definitions and basic how-to questions, such as the difference between a role and a profile. Experienced candidates get scenarios and design questions, such as how to handle data skew or design an integration, and are expected to give examples from real projects.

05

Do I need a Salesforce certification to get an interview?

It helps a lot, especially at service companies and partners, where certifications are often a filter on job descriptions. Platform Administrator for admin roles and Platform Developer for developer roles are the usual first choices. See the full list of Salesforce certifications.

Chat on WhatsApp