100 Salesforce Developer scenario-based questions and answers

Here’s a comprehensive list of 100 scenario-based interview questions and answers for a Salesforce Developer role. These cover Apex, Triggers, LWC, Integrations, Governor Limits, and real-world development scenarios.

Table of Contents

1. SOQL inside loop

Q: You find a trigger with SOQL queries inside a loop. What do you do?
A: Refactor the code by moving SOQL queries outside the loop and using collections (maps/lists) to prevent governor limit violations.


2. Field update on related object

Q: You need to update a field on the parent Account when a Contact is modified. How?
A: Use a before update trigger on Contact, and collect Account IDs. Query those Accounts, make necessary changes, and perform a DML update outside the loop.


3. Integration with external API

Q: How would you call an external REST API when a case is created?
A: Use a trigger to call a future method or Queueable Apex that performs the HTTP callout asynchronously.


4. Unique business logic

Q: A record should only be saved if a custom logic is satisfied. Validation Rule isn’t sufficient. What do you do?
A: Implement the logic in a before insert or before update trigger, throw an error using addError() on the field.


5. Deploying to production fails

Q: Deployment failed due to low test coverage. What’s your approach?
A: Review test classes, identify uncovered lines, and write additional test methods to simulate real scenarios and increase coverage.


6. Bulk record processing

Q: A trigger works for single record but fails in bulk. What’s wrong?
A: It’s not bulkified. Ensure logic uses bulk-safe patterns: avoid DML/SOQL in loops and handle records as collections.


7. Display records in UI

Q: You need to build a UI where users can edit related child records. How?
A: Use LWC with Apex to fetch data. Allow inline editing in a data table and save via Apex controller using bulk DML.


8. Governor limit exceeded

Q: A process fails due to “Too many DML statements.” How to fix?
A: Combine DML operations by batching records into a list and performing a single update or insert at the end of processing.


9. Schedule a nightly job

Q: How would you send daily reports via email?
A: Write a class implementing Schedulable, query and format the report, then send using Messaging.sendEmail(). Schedule it via UI or code.


10. Testing callouts

Q: How do you write tests for callouts?
A: Use HttpCalloutMock to simulate responses and test the logic without making actual API calls.


11. Insert logic across multiple objects

Q: You need to insert Opportunity and related custom object records in one go. How?
A: Use Apex to insert the Opportunity first, capture the ID, then assign it to related records and insert them in bulk.


12. Reusable logic

Q: Business logic is repeated across multiple triggers. What’s your solution?
A: Extract the logic into a separate Apex class (Handler) and call it from triggers. This promotes reusability and testability.


13. Rollup summary on lookup

Q: You need a rollup count on a lookup relationship. What do you do?
A: Use Apex trigger or tools like Declarative Lookup Rollup Summaries (DLRS) to handle non-master-detail rollups.


14. Update records via Flow

Q: How to update related child records when parent field changes?
A: Use a Record-Triggered Flow with Get Records + Loop + Update to handle this declaratively.


15. Prevent delete based on condition

Q: You need to block a record from being deleted if certain conditions are met. How?
A: Use a before delete trigger to check the condition and call addError() to prevent deletion.


16. Platform Event Handling

Q: How would you use Platform Events to communicate between apps?
A: Publish events from one process and subscribe in another (via Apex or external system). This decouples systems in an event-driven architecture.


17. Large data migration

Q: How would you insert 10 million records?
A: Use Batch Apex to process records in manageable chunks and ensure it adheres to governor limits.


18. Multiple triggers on same object

Q: You discover several triggers on the same object. Is this okay?
A: It’s not recommended. Combine logic into a single trigger and delegate tasks to handler classes.


19. Dynamic SOQL

Q: When and how would you use dynamic SOQL?
A: When field names or object types are determined at runtime, use Database.query() safely with bind variables to avoid injection.


20. Custom settings vs metadata

Q: When would you choose Custom Metadata over Custom Settings?
A: Custom Metadata is deployable and doesn’t count against data limits. Prefer it for config that shouldn’t change frequently.

21. Trigger recursion

Q: Your trigger is firing multiple times during a single transaction. How do you prevent recursion?
A: Use a static Boolean variable in a helper class to track whether the logic has already been executed in the current context. This prevents recursive trigger calls by ensuring the logic runs only once.


22. Null pointer exceptions in Apex

Q: Your Apex code throws a null pointer exception when accessing a record field. How do you fix it?
A: Add null checks before accessing the field. Use if(record != null && record.Field__c != null) or optional chaining (?. in LWC) to avoid errors when fields or records may not be populated.


23. Implementing polymorphism

Q: How can you use polymorphism in Apex to manage different record types with shared logic?
A: Create a virtual base class with shared methods and extend it for each record type’s custom logic. Use the base class in your main logic to handle records generically while calling the specific implementation when needed.


24. Debugging governor limit issues

Q: Your logic works fine in dev but fails in production with a limit error. What’s your approach?
A: Use the Developer Console or debug logs to track the number of SOQLs/DMLs used. Ensure no SOQL/DML statements exist inside loops. Refactor the logic using maps or batch processing if the data volume is large.


25. Calling batch from a trigger

Q: You need to process heavy logic asynchronously but only from a trigger. What do you do?
A: You can’t call batch classes directly from a trigger. Instead, enqueue a Queueable Apex job, which can call the batch class or handle the logic directly in a more controlled async context.


26. Building a custom login flow

Q: How can you implement a custom login flow to verify user agreement to terms?
A: Create a custom Lightning component or Flow and assign it via Login Flows. The logic should check for user agreement and redirect them or log them out if not accepted.


27. Locking records for update

Q: How do you lock a record to prevent it from being edited concurrently?
A: Use SELECT Id FROM Object__c WHERE Id = :recordId FOR UPDATE to lock the record during processing. This ensures safe concurrent updates.


28. Securing Apex Web Services

Q: How do you secure custom Apex REST web services?
A: Use @RestResource with named paths. Check user permissions inside the method using Schema.sObjectType.MyObject__c.isAccessible() and enforce security with custom permission sets.


29. Partial success on DML

Q: What if some records succeed and others fail during an insert?
A: Use Database.insert(records, false) to allow partial success. Then inspect the Database.SaveResult[] array to handle failures gracefully and notify users or log errors.


30. Pagination in Apex

Q: How do you build paginated results from an Apex controller?
A: Use OFFSET in SOQL and track the current page on the client side. For example, SELECT Name FROM Account LIMIT 10 OFFSET 20 for the third page.


31. Refresh LWC after save

Q: You need your LWC to reflect updated data after saving. What’s the approach?
A: Use refreshApex() if using wired data, or re-fetch the data imperatively after a successful save to ensure the component reflects latest changes.


32. Concurrent updates

Q: Two users update the same record simultaneously. How do you handle it?
A: Implement optimistic concurrency using RecordType.LastModifiedDate or SystemModstamp. Compare timestamps and warn the user if another change occurred during edit.


33. Retrieve parent-child data efficiently

Q: How do you query related records efficiently in Apex?
A: Use relationship queries (SOQL nested queries), e.g., SELECT Name, (SELECT LastName FROM Contacts) FROM Account. This reduces the number of SOQL calls.


34. Prevent updates based on record type

Q: Some record types should be read-only. How do you enforce this?
A: Use a before update trigger to check the record type. If it matches the restricted type, call addError() to block the update.


35. Reusable LWC component

Q: You need a component that can be reused across multiple objects. How do you make it generic?
A: Use @api properties to pass object name, record ID, and fields into the component. Use getRecord() or Apex to dynamically retrieve and display data.


36. Mass delete with condition

Q: You need to allow mass deletion of records, but only if a field is checked. What’s your approach?
A: Use a custom button or Flow with decision logic to check the field. If true, proceed with deletion using Apex or Flow’s delete element.


37. Programmatically share records

Q: How do you share a custom object record with another user in Apex?
A: Use the Share object (e.g., CustomObject__Share) and insert a new record with the user ID and access level (Read, Edit).


38. JSON circular references

Q: You get an error while serializing Apex objects to JSON. Why?
A: You may have circular references in your object graph. Use JSON.serialize(object, true) to handle deep cycles or refactor the object to avoid nesting loops.


39. Expose Apex to external systems

Q: You need to allow external systems to access your Salesforce logic. How?
A: Create a @RestResource class or a @WebService class depending on whether the system uses REST or SOAP. Make sure you authenticate requests via OAuth.


40. Special characters in SOQL

Q: A user enters a name with an apostrophe. Your SOQL breaks. How do you fix it?
A: Always use bind variables in dynamic SOQL to avoid manual escaping. For example: WHERE Name = :userInput safely handles special characters.

41. Display picklist values in LWC

Q: You want to show picklist values dynamically in LWC. How do you do it?
A: Use @wire(getPicklistValues, { recordTypeId: ..., fieldApiName: ... }) from lightning/uiObjectInfoApi. This provides picklist values based on the object and field.


42. Use composite REST API

Q: You want to create an Account and a related Contact in a single API call. What’s your approach?
A: Use Salesforce’s Composite REST API. It allows chained operations where the second request can reference the ID from the first response using @{referenceId.id}.


43. Multi-step screen flow

Q: A business process needs user input across multiple steps. How would you implement this?
A: Use Screen Flow with multiple screens, decisions, and conditional paths. Variables are passed between screens and decisions determine the next step.


44. Prevent duplicate records

Q: Users are creating duplicate Contacts. How can you stop this?
A: Use a before insert trigger or a duplicate rule. In Apex, query for existing Contacts with similar name/email and use addError() if a match is found.


45. Use static resources in LWC

Q: You want to load a custom JavaScript library in your component. What’s the solution?
A: Upload the JS file as a static resource, then load it in your LWC using loadScript(this, myResource) from the lightning/platformResourceLoader module.


46. Track field history in Apex

Q: How can you manually track changes to fields for auditing?
A: Use a before update trigger. Compare old and new values (Trigger.oldMap.get(Id).Field__c != new.Field__c) and log the changes to a custom history object.


47. Trigger after attachment upload

Q: You want to execute logic after a file is uploaded to a record. How?
A: Use a trigger on the ContentDocumentLink object. This allows you to act once a file is linked to a record.


48. Lazy load data in LWC

Q: Your component loads too slowly because of large data. How can you improve it?
A: Implement lazy loading. Fetch only the first batch, then load more when the user scrolls using an infinite scroll pattern or onloadmore events in lightning-datatable.


49. Memory leak in LWC

Q: Your LWC component seems to slow down the browser. What’s your approach?
A: Ensure all event listeners are removed in the disconnectedCallback() lifecycle hook and avoid unnecessary re-rendering of large data sets.


50. Validate email domain

Q: You want to ensure users don’t use personal email domains like gmail.com. How?
A: Use a trigger or validation rule to check if the email contains @gmail.com, @yahoo.com, etc., and block the save using addError() or a validation formula.


51. Invoke Apex from Flow

Q: You want Flow to execute custom logic. How can this be done?
A: Create an Apex class with the @InvocableMethod annotation. It allows Flows to call Apex and pass in data as input variables.


52. Exception in Queueable Apex

Q: Your Queueable class fails with an unhandled exception. What do you do?
A: Wrap logic in try-catch blocks inside execute() and log errors to a custom object or send alerts to admins for visibility.


53. API limits hit

Q: You’re hitting API limits due to frequent external integrations. What’s your solution?
A: Use Platform Events or Change Data Capture to reduce polling. Also, implement caching and batch integration requests where possible.


54. Restrict trigger logic by profile

Q: You want a trigger to run only for users with specific profiles. Can you do this?
A: Use UserInfo.getProfileId() in the trigger context and compare it against allowed profiles. However, avoid using business logic filters in triggers if it can be handled in Flows or user permissions.


55. Schedule a class from trigger

Q: You need to delay logic but the call starts from a trigger. What’s the best option?
A: Enqueue a Queueable class from the trigger. Queueables can be chained or scheduled if needed—unlike batch or scheduled Apex which can’t be called directly.


56. Chain batch jobs

Q: How do you run batch jobs sequentially?
A: Use Database.executeBatch() and in the finish() method of the first batch, call the next batch. This ensures sequential execution.


57. Setup wizard in LWC

Q: You’re building a step-by-step setup UI. How do you approach it?
A: Use LWC with multiple conditional sections controlled by step variables (currentStep). Each “Next” click moves to the next logical component section.


58. Managed package Apex

Q: You’re developing Apex for a managed package. What considerations do you take?
A: Avoid hardcoded IDs. Use with sharing or without sharing appropriately. Expose methods with global instead of public, and make code namespace-aware.


59. AuraEnabled security

Q: Your Apex class is exposed to LWC but shows “Access Denied”. Why?
A: Ensure the Apex class is marked with @AuraEnabled and with sharing. Also, check the user has CRUD/FLS access to referenced objects/fields.


60. Query deleted records

Q: You need to retrieve soft-deleted records. How?
A: Use ALL ROWS or FOR RECYCLE BIN in your SOQL query. Example: SELECT Name FROM Account WHERE IsDeleted = true ALL ROWS.

61. Custom Clone Button

Q: You need to create a custom button to clone a record with some changes. How would you do that?
A: Use a Quick Action or custom button that calls Apex. In Apex, query the existing record, modify desired fields, and insert a new record. Redirect the user to the new record using a PageReference.


62. Handle Email Bounces

Q: How do you track bounced emails sent from Salesforce?
A: Use the EmailMessage and BounceNotification objects. Set up email relay or bounce management and query the BounceReason and BounceDate for tracking.


63. Test trigger on undeletable object

Q: You need to write test coverage for a delete trigger on an object you can’t delete in real orgs. What do you do?
A: In test methods, you can create and delete records without worrying about constraints like in production. Use @isTest context to simulate delete operations.


64. Optimize slow SOQL

Q: Your query is taking too long. What do you do?
A: Use selective filters on indexed fields, reduce the number of fields selected, avoid LIKE '%text%', and ensure queries don’t hit large joins or nested subqueries without limits.


65. Uncommitted work exception

Q: You get “Uncommitted work pending” when doing a callout. What happened?
A: You’re performing DML before a callout. Move all DML after the callout or use @future or Queueable to separate the callout from the transaction.


66. Pass data between components

Q: You have multiple LWCs on the same page and want to pass data. How?
A: Use a Lightning Message Service (LMS) for sibling components or parent-child communication using @api properties and custom events.


67. Compare Custom Metadata

Q: You need to check custom rules stored in metadata during a trigger. How do you do it?
A: Query the custom metadata using SELECT DeveloperName, Value__c FROM CustomMetadata__mdt and cache results in maps for efficiency.


68. Secure custom API

Q: You built a custom Apex REST API. How do you restrict access?
A: Use OAuth scopes and check user permissions inside the method. Consider validating API keys or session contexts and returning 403 if unauthorized.


69. Avoid hardcoded IDs

Q: You’re referencing a record type by ID in code. What’s the better approach?
A: Use Schema.SObjectType.MyObject__c.getRecordTypeInfosByName().get('MyRecordType').getRecordTypeId() to fetch the ID dynamically.


70. Prevent concurrent batch jobs

Q: Two admins accidentally schedule the same batch job. How do you avoid this?
A: Check for existing jobs using System.abortJob() or query AsyncApexJob to avoid duplicate runs. You can also set a custom flag in a Custom Setting to manage locks.


71. Deploy Record Types

Q: You need to deploy record types from sandbox to production. How?
A: Use Change Sets or Salesforce CLI (metadata API) to deploy RecordType, ensuring the correct Profiles are also included for access control.


72. Dynamically assign Record Types

Q: How do you assign a record type based on user profile in Apex?
A: In your Apex logic, query the desired RecordType by developer name and assign it based on the user’s profile using UserInfo.getProfileId().


73. Format complex JSON in Apex

Q: You need to send a nested JSON body to an external API. How?
A: Create a wrapper class with inner classes matching the JSON structure. Use JSON.serialize(wrapperObject) to convert it properly.


74. Debug async processes

Q: How do you troubleshoot issues in Queueable or Batch jobs?
A: Use System.debug(), log errors to a custom object, or set debug logs for the Apex job user. Monitor with AsyncApexJob or ApexJob records.


75. Conditional UI in LWC

Q: You want to show/hide components based on field values. What’s the best way?
A: Use tracked variables and expressions in the HTML template. For example: <template if:true={showSection}>.


76. Prevent reprocessing of events

Q: Your Platform Event subscriber sometimes processes the same event multiple times. How do you prevent it?
A: Track processed event GUIDs in a custom object or cache and ignore duplicates. Use ReplayId to ensure ordering in external systems.


77. Build Apex REST Service

Q: You need to expose an Apex class for external use. How do you do it?
A: Create a class with @RestResource(urlMapping='/myendpoint/*'), use @HttpPost, @HttpGet methods and parse RestRequest.reqBody as needed.


78. Return JSON from LWC

Q: Your Apex method should return structured JSON to an LWC. How?
A: Return an object or a map, then use JSON.serialize() in Apex or parse the returned object directly in JS. LWC handles it as a JS object.


79. Schedule Platform Events

Q: You want to publish events on a schedule. What do you do?
A: Write a Schedulable class that fires every night using EventBus.publish(). Schedule it using System.schedule().


80. Dynamic field visibility in LWC

Q: You want to hide a field unless a picklist has a specific value. What’s the best approach?
A: Use reactive tracked variables or @wire data and evaluate the value with if:true or if:false directives in the template.

81. Use wire service with filters

Q: You want your LWC to filter data based on user input. How do you implement this with wire?
A: Use @wire(apexMethod, { searchKey: '$searchKey' }). The $ denotes reactivity, so when searchKey changes, the wire method re-runs automatically.


82. Clone deep object trees

Q: You need to clone an Opportunity with all its related Products. How would you do this?
A: Query the parent and child records. Create deep copies using Apex, reset the IDs, adjust relationships (like OpportunityId), and insert them in bulk to maintain links.


83. Trigger framework

Q: You want to standardize all trigger logic across the org. What’s your solution?
A: Use a trigger handler framework. Each trigger delegates logic to a handler class that implements logic based on context (isInsert, isUpdate, etc.), improving maintainability and testing.


84. Store temporary user selections

Q: You need to store a user’s temporary selections during a multi-screen process. Where?
A: Use Lightning component attributes (LWC variables), Flow variables, or store it in a custom object if persistence across sessions is required.


85. Track background job status

Q: How can you show users the status of an Apex batch process?
A: Query AsyncApexJob to get status and percentage. Display the info on a Visualforce page or LWC for real-time feedback.


86. Log errors to custom object

Q: How do you handle and persist errors in Apex?
A: Use try-catch blocks and insert error details into a custom object (e.g., Error_Log__c) for auditing and troubleshooting.


87. Query archived records

Q: You need to query Tasks and Events older than a year. They aren’t showing up. Why?
A: Use ALL ROWS or FOR VIEW in your SOQL. Salesforce archives old activities, and these flags allow access to historical data.


88. OAuth integration

Q: How would you connect Salesforce with a third-party app that uses OAuth 2.0?
A: Register a Connected App, exchange authorization codes for tokens, and use named credentials or custom callout logic to securely access APIs.


89. Business rules in metadata

Q: You want to allow admins to control validation rules without code. How?
A: Store business logic in Custom Metadata or Custom Settings and query them in Apex or Flows. This allows admins to toggle or update behavior declaratively.


90. Load thousands of rows in UI

Q: Your LWC must display 10,000 records. How do you make this performant?
A: Use server-side pagination and lazy loading. Fetch 100–200 records at a time as users scroll, reducing the initial load.


91. Process Excel files in Apex

Q: A user uploads an Excel file. How do you parse it in Apex?
A: Convert Excel to CSV before upload. Parse the CSV using String.split() and process records row by row.


92. Trigger on public site form

Q: You want to run logic after a user submits a form on a public site. How?
A: Create a before insert trigger on the form’s target object. Make sure guest users have minimal required permissions for execution.


93. Multi-step approval logic

Q: A process requires conditional approvals. How would you set this up?
A: Use a custom approval process with entry criteria and multiple approval steps. You can also invoke Apex from ProcessInstance for advanced scenarios.


94. Apex CPU timeout

Q: Your code is hitting Apex CPU limits. What now?
A: Optimize logic: reduce nested loops, avoid unnecessary SOQL/DML, use maps for lookups, and consider async processing for heavy computations.


95. Render charts in LWC

Q: You need to display charts in a Lightning component. How?
A: Use Chart.js as a static resource or leverage Lightning App Builder chart components. In LWC, dynamically build datasets and render via canvas.


96. Handle orphaned records

Q: You notice child records exist without a parent. How do you prevent this?
A: Use lookup filters with Required enforcement or use a trigger to check for parent record presence before insert/update.


97. Lead conversion with custom fields

Q: You want to map a custom field from Lead to Account on conversion. How?
A: Set up field mapping via Setup → Lead Mapping, or use Apex for more complex logic in a trigger on Lead or post-conversion automation.


98. Validate date relative to today

Q: A field should only accept dates in the future. How do you enforce it?
A: Use a validation rule: Date__c < TODAY() and show an error like “Date must be in the future.”


99. Use custom permissions in Apex

Q: How can you check if a user should access a feature?
A: Create a Custom Permission, assign it via permission sets, and use FeatureManagement.checkPermission('Your_Permission') in Apex.


100. Retry logic for callouts

Q: An HTTP callout fails occasionally. How do you implement retries?
A: Use exponential backoff logic in Apex. Retry the callout up to a maximum number of times, spacing out retries (use recursive Queueable if needed).

You may also like...