0% found this document useful (0 votes)
43 views42 pages

Salesforce Developer Interview Guide

Uploaded by

timelass13
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views42 pages

Salesforce Developer Interview Guide

Uploaded by

timelass13
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Salesforce Interview Question

Apex, LWC, SOQL/SOSL, data model/security, integration, and automation.

Introduction (3 minutes)
• Interviewer: "Welcome! Please introduce yourself and briefly describe
your Salesforce development experience."
• Candidate: (Shares background, projects, skills)

Apex Programming (5 minutes)


• Interviewer: "How do you handle governor limits in Apex? Can you give
examples of best practices?"
• Candidate: (Explains bulkification, avoiding queries/DML inside loops,
asynchronous Apex)
• Interviewer: "Describe how you would bulkify an Apex trigger and why
it's important."
• Candidate: (Explains trigger framework, collections, bulk data processing)

Lightning Web Components (LWC) (4 minutes)


• Interviewer: "What are the main differences between Lightning Web
Components and Aura components?"
• Candidate: (Describes modern standards-based approach of LWC, better
performance)
• Interviewer: "How do you handle communication between parent and
child components in LWC?"
• Candidate: (Explains @api, custom events)

SOQL and SOSL (4 minutes)


• Interviewer: "What is the difference between SOQL and SOSL, and when
would you use each?"
• Candidate: (Explains SOQL for object-specific queries, SOSL for text
search across objects)
• Interviewer: "How do you optimize SOQL queries to avoid hitting
governor limits?"
• Candidate: (Use selective filters, limit fields queried, avoid nested
queries)

Data Model and Security (4 minutes)


• Interviewer: "Explain the difference between profiles and permission
sets."
• Candidate: (Profiles define base permissions, permission sets add extra
privileges)
• Interviewer: "What are master-detail and lookup relationships? How do
they impact data security?"
• Candidate: (Master-detail inherits security from parent, lookup allows
independent record access)

Integration (5 minutes)
• Interviewer: "What are Named Credentials, and why are they important?"
• Candidate: (Used to simplify authentication and secure API calls)
• Interviewer: "Describe a Salesforce integration you worked on and key
challenges."
• Candidate: (Shares example, handling data sync, error handling, secure
callouts)

Automation (5 minutes)
• Interviewer: "What are the differences between Workflow Rules, Process
Builder, and Flow?"
• Candidate: (Describes features, limitations, when to use each)
• Interviewer: "How do you handle error handling and governor limits in
Flows?"
• Candidate: (Fault paths, bulkification considerations)

Developer Technical Topics


I. Apex Programming: - Advanced triggers, classes, interfaces, bulkification,
asynchronous Apex (Batch, Queueable, Future).

II. Lightning Development: Lightning Web Components (LWC), Aura Components,


component communication.

III. SOQL and SOSL: Complex queries, relationship queries, optimization.


IV. Salesforce Data Model & Security: Custom and standard objects, relationships,
sharing rules, profiles, and permission sets.

V. Integration: REST and SOAP APIs, Named Credentials, and middleware


understanding.

VI. Automation: Declarative tools such as Flows, Process Builder, Workflow Rules.
VII. Testing & Deployment: Apex test classes, Salesforce DX, sandboxes, change sets,
deployment best practices.

VIII. Performance: Handling governor limits, efficient data processing.


IX. DevOps: Source control, CI/CD, agile development.

Admin Technical Topics


I. User Management: Profiles, permission sets, role hierarchy, public groups, and
licenses.
II. Security & Sharing: Organization-wide defaults (OWD), sharing rules, field-level
security, and record-level access.

III. Data Management: Data import/export tools (Data Loader, Data Import Wizard),
data validation rules, duplicate management.

IV. Salesforce Setup & Configuration: Custom objects, fields, page layouts, record
types, and apps.

V. Automation Tools: Workflow rules, process builder, approval processes, and


Salesforce Flows.

VI. Reports & Dashboards: Creating and optimizing custom reports, dashboards, and
analytic snapshots.

VII. Change Management: Sandboxes management, release cycles, change sets.


VIII. Salesforce Platform Features: Understanding of Sales Cloud, Service Cloud, and
other relevant clouds for better end-to-end solutions.

Apex Programming
1. How do you ensure your Apex code is bulkified, and why is it important?
2. Explain the differences and use cases of Lightning Web Components
(LWC) versus Aura components.
3. Describe a complex integration you have implemented using Salesforce
APIs. What challenges did you face?
4. How do you handle governor limits in Salesforce, and what techniques do
you use to avoid hitting them?
5. What is your approach to writing Apex test classes? How do you ensure
high code coverage and quality?
6. Explain the Salesforce security model, including roles, profiles,
permission sets, and sharing rules.
7. When would you choose Flow or Process Builder over Apex for
automation? Provide an example.
8. Describe how you manage deployments and version control in your
Salesforce projects.
9. Can you share a scenario where you debugged a difficult issue in
Salesforce? What steps did you follow?
10. How do you optimize SOQL queries for performance in your Apex
code?

Lightning Web Component


1. What are the key differences between Lightning Web Components (LWC)
and Aura Components?
2. Explain the lifecycle hooks in LWC and their typical use cases.
3. How do you handle communication between parent and child
components in LWC?
4. What are the different ways to communicate between two sibling
Lightning Web Components?
5. How do you import and use Apex methods in LWC?
6. Explain how to handle asynchronous calls and promise handling in LWC.
7. How do you manage state within an LWC component?
8. What are the security considerations when developing LWCs, especially
regarding data access and DOM manipulation?
9. How do you handle component styling and CSS encapsulation in Lightning
Web Components?
10. Describe an optimization technique you have used to improve the
performance of Lightning Web Components.

SOQL Questions
1. What is SOQL, and how is it different from traditional SQL?
2. How do you query parent-to-child and child-to-parent relationships using
SOQL?
3. How do you use the LIMIT clause in SOQL? Give an example.
4. What is the difference between Static and Dynamic SOQL, and when
would you use each?
5. How do you query deleted records in Salesforce with SOQL?
6. Explain how you would optimize SOQL queries to avoid hitting governor
limits.
7. How can you filter records using the WHERE clause in SOQL?

SOSL Questions
8. What is SOSL, and how is it different from SOQL?
9. When would you use SOSL instead of SOQL? Provide scenarios.
10. How do you write an SOSL query to search across multiple objects?

Data Model Questions


1. What are the main types of relationships in Salesforce? Explain Master-
Detail and Lookup relationships.
2. What happens to child records when a master record is deleted in a
Master-Detail relationship?
3. What is a junction object, and when would you use it?
4. Explain the difference between Standard and Custom objects.
5. What is data skew, and how can it impact performance in Salesforce?
6. What are External IDs, and how are they useful in data integration?

Security Questions
7. How does Salesforce’s role hierarchy affect record-level access?
8. What is the difference between profiles and permission sets?
9. Explain the organization-wide default (OWD) sharing model and how it
can be customized.
10. How do you enforce field-level security in Salesforce?

Integration
1. What are the different types of Salesforce integrations?
2. How do REST API and SOAP API differ in Salesforce, and when would you
use each?
3. What are Named Credentials, and why are they important in integrations?
4. Explain the difference between Outbound Messaging and Apex Callouts.
5. Describe how you authenticate an external system with Salesforce.
6. How do you handle large data volumes in Salesforce integrations?
7. What is middleware, and what role does it play in Salesforce integrations?
8. How do you ensure data consistency between Salesforce and an external
system?
9. How do you troubleshoot and debug Salesforce integration issues?
10. Explain the use of Platform Events in Salesforce integrations.

Automation
1. What are the differences between Workflow Rules, Process Builder, and
Flow in Salesforce automation?
2. When would you choose to use Flow over Process Builder or Apex
triggers?
3. How do you handle error handling and fault paths in Salesforce Flows?
4. Describe a complex automation project you worked on and the challenges
you faced.
5. How do you optimize Flows to handle large data volumes and avoid
governor limits?
6. What is an invocable Apex method, and how is it used in Flow?
7. How would you design a Flow to update related records automatically?
8. How can you schedule a Flow to run at specific times or intervals?
9. Explain the difference between Record-Triggered Flows and Schedule-
Triggered Flows.
10. How do you ensure user adoption and usability in screen Flows?

Testing & Deployment

1. What is the purpose of Apex test classes, and what are the key requirements for
writing them?

2. How do you achieve code coverage in Apex, and what is the minimum coverage
required for deployment?

3. Explain the difference between [Link] and [Link] in Apex tests.

4. What are [Link]() and [Link]() methods used for in test classes?

5. How do you handle test data creation in Apex test classes?

6. What is Salesforce DX, and how does it improve the development and deployment
process?

7. Can you explain the different types of sandboxes in Salesforce and their use cases?

8. How do change sets work in Salesforce, and what are their limitations?

9. Describe best practices for deploying metadata between Salesforce orgs.

10. How do you troubleshoot deployment failures in Salesforce? What steps do


you follow?

performance
1. What are Salesforce governor limits, and why are they important in Apex
development?

2. Can you explain common governor limits related to SOQL queries and DML
operations?

3. How do you avoid hitting the "Too many SOQL queries: 101" governor limit in Apex
triggers?

4. What is bulkification, and how does it help in handling governor limits?

5. Describe how you optimize Apex code to stay within CPU time limits.

6. How do you handle large data volumes in Salesforce while respecting governor
limits?

7. What best practices do you follow when writing triggers to prevent recursive calls
and hitting limits?

8. Explain the role of Batch Apex in processing large datasets efficiently.

9. How do you monitor and debug governor limit issues during development?

10. What techniques do you use to optimize SOQL queries for performance?

Change Management

1. What are the different types of Salesforce sandboxes, and when would you use each
type in a release cycle?

2. How do you manage sandbox refresh schedules to minimize disruption in your


development and testing workflows?

3. Can you explain the purpose of change sets and what their limitations are in
deployment?

4. Describe best practices for managing metadata and configuration changes across
multiple sandboxes before deploying to production.

5. How do you handle post-refresh tasks in sandboxes, such as masking sensitive data
or updating endpoints?

Answers for your Apex programming interview questions


1. How do you ensure your Apex code is bulkified, and why is it important?

Bulkification refers to designing Apex code to process multiple records simultaneously, rather than one at
a time. It’s important because Salesforce imposes governor limits to ensure resource sharing in the multi-
tenant environment. Bulkified code reduces the number of SOQL queries and DML operations, avoiding
hitting limits and improving performance.

To bulkify, use collections like Lists, Sets, or Maps to handle multiple records. Move SOQL queries and
DML statements outside of loops. For example, rather than querying inside a loop for each record, collect
record IDs first and run a single query for all related records. Similarly, accumulate records to update in a
list, then perform one bulk DML operation.

2. Explain the differences and use cases of Lightning Web Components (LWC) versus Aura
components.

LWCs are built on modern web standards and optimized for better performance and faster rendering
than Aura components. They use standard JavaScript, making them easier to learn and maintain. Aura
components provide a more mature framework with a wider range of base components but can be slower
and more complex.

Use LWC for new development, especially when performance, modern browser support, and
maintainability are priorities. Aura components are useful when working with legacy code or when LWC
features don’t yet cover specific use cases.

3. Describe a complex integration you have implemented using Salesforce APIs. What challenges
did you face?

I worked on integrating Salesforce with an external ERP system using REST APIs. Key challenges included
handling authentication securely, managing large data volumes without hitting governor limits, and
ensuring data consistency during sync processes. We used Named Credentials for secure authentication
and implemented batch processing and retry logic to handle failures. Mapping data fields and handling
different data models across systems also required careful transformation logic.

4. How do you handle governor limits in Salesforce, and what techniques do you use to avoid
hitting them?

I always design Apex to be bulkified, avoiding SOQL and DML inside loops. I leverage collections for
efficient data processing and use asynchronous Apex (Batch, Queueable) when processing large data sets.
I optimize SOQL queries by filtering records and retrieving only necessary fields. I monitor debug logs
and use limits methods to proactively check consumption. When limits are close, I refactor code to reduce
queries and DML or split processing into batches.

5. What is your approach to writing Apex test classes? How do you ensure high code coverage and
quality?
I write test classes that cover positive, negative, and boundary cases, ensuring over 75% code coverage. I
create necessary test data within the test methods using static resources or setup logic. I use
[Link]() and [Link]() to simulate governor limits and asynchronous processing. I assert
expected outcomes explicitly to catch failures early. I also follow best practices like using
SeeAllData=false and avoiding dependencies on org data.

6. Explain the Salesforce security model, including roles, profiles, permission sets, and sharing
rules.

Profiles define base user permissions and object-level access. Permission sets extend these permissions
without changing profiles, allowing more granular control. Roles define record-level sharing based on an
organization's hierarchy, controlling visibility of records. Sharing rules further open access by defining
exceptions to the default sharing model (OWD). Layering these elements enables flexible, secure access
tailored to business needs.

7. When would you choose Flow or Process Builder over Apex for automation? Provide an
example.

Flow and Process Builder are declarative tools ideal for simple to moderately complex automations
without code. Use Flow or Process Builder when requirements involve simple record creation, updates, or
sending notifications.

For example, a Process Builder can update a related record when an opportunity stage changes. If the
automation requires complex logic, loops, or integrations, Apex is more appropriate.

8. Describe how you manage deployments and version control in your Salesforce projects.

I use Salesforce DX and Git for source-driven development. Developers work in scratch orgs or sandboxes,
committing changes to Git repositories. CI/CD tools automate validation, testing, and deployment. Change
sets are used for smaller teams or quick deployments but are limited in automation. I ensure proper
branching strategies and code reviews to maintain code quality and coordination.

9. Can you share a scenario where you debugged a difficult issue in Salesforce? What steps did you
follow?

Once, a trigger was causing unexpected record updates leading to data inconsistencies. I enabled debug
logs for the user, analyzed log outputs to trace the execution flow, and identified SOQL queries inside
loops causing repeated unintended updates. I refactored the trigger by bulkifying code and adding flags to
prevent recursion, resolving the issue.

10. How do you optimize SOQL queries for performance in your Apex code?

I select only the fields necessary instead of ‘SELECT *’. I use selective filters and indexed fields in WHERE
clauses to reduce returned rows. I avoid nested queries unless necessary and use relationship queries
efficiently. When querying large data sets, I implement pagination or batch processing. I also use Query
Plan Tool to analyze and improve query performance.

Answers for your Lightning Web Components (LWC) interview questions:

1. What are the key differences between Lightning Web Components (LWC) and Aura
Components?

LWC uses modern web standards (HTML, ES6+ JavaScript), offers faster performance, simpler syntax, and
better maintainability. Aura is an older framework with its own event system and heavier rendering
overhead, mainly used for legacy apps. LWC is recommended for new development.

2. Explain the lifecycle hooks in LWC and their typical use cases.

• constructor(): Initializes component instance.

• connectedCallback(): Called when the component is inserted into the DOM; used for fetching data
or setup.

• renderedCallback(): Called after each render; used for DOM manipulations.

• disconnectedCallback(): Called when the component is removed; cleanup operations.

• errorCallback(): Handles errors during rendering.

3. How do you handle communication between parent and child components in LWC?

The parent uses the @api decorator to expose properties/methods that the child can access. The child
notifies parent components by dispatching custom events which the parent listens to.

4. What are the different ways to communicate between two sibling Lightning Web Components?

Use a common parent component to mediate communication by event dispatching or leverage pub/sub
patterns with an event bus module to communicate without direct hierarchy.

5. How do you import and use Apex methods in LWC?

Import Apex methods using @salesforce/apex and then call them imperatively using promises or wire
adapters for reactive data.

Example:

js
import getAccounts from '@salesforce/apex/[Link]';

getAccounts()

.then(result => { /* handle result */ })

.catch(error => { /* handle error */ });

6. Explain how to handle asynchronous calls and promise handling in LWC.

Use JavaScript promises with .then() and .catch() for async Apex calls or async/await syntax for better
readability. Handle errors gracefully and update the component state after promise resolution.

7. How do you manage state within an LWC component?

Use reactive properties marked with @track (deprecated in latest LWC) or simply class fields for
primitive values. State changes trigger rerendering.

8. What are the security considerations when developing LWCs, especially regarding data access
and DOM manipulation?

Prevent Cross-Site Scripting (XSS) by sanitizing user inputs. Use Lightning Data Service or Apex to enforce
CRUD/FLS checks. Avoid direct DOM manipulation outside safe methods and leverage Locker Service
protections.

9. How do you handle component styling and CSS encapsulation in Lightning Web Components?

LWC uses Shadow DOM to encapsulate styles, preventing leakage. Styles are scoped to components. Use
static css files with components and leverage Lightning Design System (SLDS) classes for consistent
styling.

10. Describe an optimization technique you have used to improve the performance of Lightning
Web Components.

Implemented lazy loading for data-heavy components, debounced input handlers to reduce unnecessary
processing, and minimized the number of reactive properties to reduce rerender cycles, improving UI
responsiveness and load times.

Answers for the SOQL and SOSL interview questions:

1. What is SOQL, and how is it different from traditional SQL?


SOQL (Salesforce Object Query Language) is Salesforce’s query language for retrieving records
from Salesforce objects. Unlike SQL, SOQL does not support INSERT/UPDATE/DELETE commands
and does not allow SELECT *. It uses relationship queries instead of joins and respects Salesforce
security settings and governor limits.

2. How do you query parent-to-child and child-to-parent relationships using SOQL?

• Parent-to-child: Use subqueries with the child relationship name:


SELECT Name, (SELECT LastName FROM Contacts) FROM Account

• Child-to-parent: Use dot notation to access parent fields:


SELECT FirstName, LastName, [Link] FROM Contact

3. How do you use the LIMIT clause in SOQL? Give an example.


The LIMIT clause restricts the number of records returned. Example:
SELECT Name FROM Account WHERE Industry = 'Technology' LIMIT 10

4. What is the difference between Static and Dynamic SOQL, and when would you use each?

• Static SOQL: Query is hardcoded in Apex, safer and easier to maintain. Used when query is known
at compile time.

• Dynamic SOQL: Query is constructed as a string at runtime, useful for flexible or conditional
querying.

5. How do you query deleted records in Salesforce with SOQL?


Use the ALL ROWS keyword to include deleted (soft deleted) records:
SELECT Id, Name FROM Account WHERE IsDeleted = true ALL ROWS

6. Explain how you would optimize SOQL queries to avoid hitting governor limits.
Select only necessary fields, use selective filters on indexed fields, avoid queries inside loops, use
relationship queries efficiently, and leverage query pagination for large datasets.

7. How can you filter records using the WHERE clause in SOQL?
Use the WHERE clause with field operators (=, !=, <, >, IN, LIKE, etc.) to filter records based on
conditions, e.g.:
SELECT Name FROM Contact WHERE Email LIKE '%@[Link]'

SOSL Questions

8. What is SOSL, and how is it different from SOQL?


SOSL (Salesforce Object Search Language) is designed for full-text search across multiple objects
and fields simultaneously. SOQL queries records in a single object or related objects. SOSL is useful
for searching text strings, SOQL for precise queries.

9. When would you use SOSL instead of SOQL? Provide scenarios.


Use SOSL when you want to search for a term across multiple objects or fields, e.g., searching a
customer’s name in Contacts, Leads, and Accounts at once.

10. How do you write an SOSL query to search across multiple objects?
Example:
FIND {John} IN ALL FIELDS RETURNING Contact(Id, Name), Account(Id, Name)
Answers for Data Model and Security interview questions

Data Model Questions

1. What are the main types of relationships in Salesforce? Explain Master-Detail and Lookup
relationships.
Master-Detail is a tight relationship where the child record’s existence depends on the parent;
deleting the parent deletes the child, and security is inherited. Lookup is a loose relationship
allowing independent record existence; deleting the parent does not delete the child unless
configured.

2. What happens to child records when a master record is deleted in a Master-Detail


relationship?
All child records are automatically deleted (cascade delete) when the master record is deleted in a
Master-Detail relationship.

3. What is a junction object, and when would you use it?


A junction object is a custom object with two Master-Detail relationships to create a many-to-many
relationship between two objects, used when a record relates to multiple records in each related
object.

4. Explain the difference between Standard and Custom objects.


Standard objects are Salesforce-provided (e.g., Account, Contact), while Custom objects are created
by users to store additional data unique to their business needs.

5. What is data skew, and how can it impact performance in Salesforce?


Data skew occurs when many child records are associated with a single parent, causing record
locking and performance issues during updates or sharing recalculations.

6. What are External IDs, and how are they useful in data integration?
External IDs are custom fields marked to hold unique identifiers from external systems, facilitating
upsert operations and matching records during integration without relying on Salesforce record
IDs.

Security Questions

7. How does Salesforce’s role hierarchy affect record-level access?


Role hierarchy grants record access by allowing users higher in the hierarchy to access records
owned by users below them, enabling data visibility aligned with organizational structure.

8. What is the difference between profiles and permission sets?


Profiles define baseline permissions and object-level access for users; permission sets grant
additional permissions without changing profiles, allowing flexible access control.

9. Explain the organization-wide default (OWD) sharing model and how it can be customized.
OWD sets the default record access level (private, public read, or read/write). Custom sharing
rules and role hierarchy can extend access beyond OWD defaults.
10. How do you enforce field-level security in Salesforce?
Field-level security is enforced via profiles or permission sets by specifying field read/write
permissions, ensuring sensitive data is accessible only to authorized users.

Answers to your Salesforce integration interview questions

Integration Questions

1. What are the different types of Salesforce integrations?


Types include data integrations (ETL, batch data loads), application integrations (REST/SOAP
APIs), UI integrations (Embedded components), and process integrations (Platform Events,
outbound messaging).

2. How do REST API and SOAP API differ in Salesforce, and when would you use each?
REST API is lightweight, uses JSON, and is easier for web/mobile integration. SOAP API is protocol-
heavy, XML-based, suited for enterprise-level, formal contracts, and operations requiring higher
security or transactional compliance.

3. What are Named Credentials, and why are they important in integrations?
Named Credentials store endpoint URLs and authentication details securely, simplifying
authentication and connection management for external systems, reducing callout complexity.

4. Explain the difference between Outbound Messaging and Apex Callouts.


Outbound Messaging is a declarative feature sending SOAP messages on record changes without
code; Apex Callouts are programmatic HTTP or SOAP requests invoked from Apex for custom
integration logic.

5. Describe how you authenticate an external system with Salesforce.


Use OAuth 2.0 for secure token-based authentication, Username-Password flow for server-to-
server, or JWT for delegated authentication. Named Credentials simplify this by managing tokens
automatically.

6. How do you handle large data volumes in Salesforce integrations?


Use Batch Apex for asynchronous bulk data processing, chunk data into smaller batches, employ
Bulk API for large data loads, and handle retries and error logging.

7. What is middleware, and what role does it play in Salesforce integrations?


Middleware acts as a bridge between Salesforce and external systems, handling data
transformation, orchestration, routing, and error handling for smoother integration.

8. How do you ensure data consistency between Salesforce and an external system?
Implement transactional operations, use middleware for reliable message queuing, reconciliation
jobs, error monitoring, and employ locks or versioning to prevent conflicts.

9. How do you troubleshoot and debug Salesforce integration issues?


Use debug logs for Apex callouts, monitor API usage, check external system logs, validate endpoint
accessibility, and employ error handling in code with detailed logging.
10. Explain the use of Platform Events in Salesforce integrations.
Platform Events enable event-driven, asynchronous integrations where Salesforce can publish or
subscribe to events, facilitating decoupled communication between systems.

Answers to Salesforce automation interview questions

Automation Questions
1. What are the differences between Workflow Rules, Process Builder, and Flow in Salesforce
automation?
Workflow Rules are simple and limited to field updates, email alerts, and tasks. Process Builder
offers more complex automations including record creation and invocation of Flows. Flow is the
most powerful, supporting complex logic, user interaction, and integration with Apex.

2. When would you choose to use Flow over Process Builder or Apex triggers?
Use Flow for complex multi-step automations requiring user interaction or updates to related
records without code. Apex is preferred when logic is too complex or performance-critical, and
Process Builder for simpler record-based automations.

3. How do you handle error handling and fault paths in Salesforce Flows?
Configure fault paths on elements like record updates or Apex calls to capture errors. Use fault
paths to notify admins, log errors, or perform corrective actions.

4. Describe a complex automation project you worked on and the challenges you faced.
Implemented a multi-step approval process with record updates and notifications using Flows.
The challenge was handling bulk limits and ensuring data consistency, addressed by batching and
careful flow design.

5. How do you optimize Flows to handle large data volumes and avoid governor limits?
Avoid excessive DMLs by consolidating updates, use scheduled or batch flows for large datasets,
and minimizing queries by passing variables effectively.

6. What is an invocable Apex method, and how is it used in Flow?


An Apex method annotated with @InvocableMethod can be called from Flow to perform complex
logic not achievable declaratively.

7. How would you design a Flow to update related records automatically?


Use Record-Triggered Flow, query related records with Get Records, loop through them and
update in a bulk-friendly collection, then perform a single update operation.

8. How can you schedule a Flow to run at specific times or intervals?


Use Scheduled Flows triggered by time-based criteria to automate periodic tasks.

9. Explain the difference between Record-Triggered Flows and Schedule-Triggered Flows.


Record-Triggered Flows execute immediately after a record is created or updated. Scheduled
Flows run at specified times or intervals independent of record changes.
10. How do you ensure user adoption and usability in screen Flows?
Design intuitive UI with clear instructions, minimize steps, validate inputs, and gather user
feedback for continuous improvement.

Answer for Testing & Deployment, Performance

1. What is the purpose of Apex test classes, and what are the key requirements for writing
them?
Apex test classes verify code correctness, prevent regressions, and are required for deployment.
They must include test methods with test data, assert expected outcomes, and not depend on org
data.

2. How do you achieve code coverage in Apex, and what is the minimum coverage required for
deployment?
Write comprehensive tests covering positive, negative, and edge cases, aiming for over 75% code
coverage, which is the Salesforce minimum for deployment.

3. Explain the difference between [Link] and [Link] in Apex tests.


[Link] validates conditions and causes test failures if conditions are false; [Link]
logs information for debugging but doesn’t affect test outcomes.

4. What are [Link]() and [Link]() methods used for in test classes?
They reset governor limits during testing and allow execution of asynchronous code
synchronously for accurate testing.

5. How do you handle test data creation in Apex test classes?


Create all test records within test methods to avoid dependencies on org data and ensure test
isolation.

6. What is Salesforce DX, and how does it improve the development and deployment process?
Salesforce DX provides modern CLI tools, source-driven development, scratch orgs for isolated
dev, and integration with CI/CD for automated deployments.

7. Can you explain the different types of sandboxes in Salesforce and their use cases?
Types include Developer (small dev/testing), Developer Pro (larger dev/testing), Partial Copy
(partial production data for QA), and Full (copy of production for staging).

8. How do change sets work in Salesforce, and what are their limitations?
Change sets allow metadata deployment between related orgs using a GUI but lack automation,
support limited metadata types, and aren’t ideal for complex CI/CD.

9. Describe best practices for deploying metadata between Salesforce orgs.


Use source control, automated CI/CD pipelines with Salesforce DX, validate in sandboxes, run
tests, use change sets for minor changes, and document deployments.

10. How do you troubleshoot deployment failures in Salesforce? What steps do you follow?
Analyze error messages, fix validation or test failures, check dependencies and metadata types,
rerun failed tests, and use deployment logs for diagnosis.
Performance

1. What are Salesforce governor limits, and why are they important in Apex development?
Limits prevent resource monopolization in a multi-tenant environment, ensuring platform
stability and fair resource allocation.

2. Can you explain common governor limits related to SOQL queries and DML operations?
Limits include max 100 SOQL queries and 150 DML operations per transaction, enforcing efficient
resource use.

3. How do you avoid hitting the "Too many SOQL queries: 101" governor limit in Apex
triggers?
Bulkify code by moving SOQL queries outside loops and using collections to query all needed data
in one call.

4. What is bulkification, and how does it help in handling governor limits?


Writing code to process multiple records at once reduces the number of SOQL/DML operations,
preventing limit breaches.

5. Describe how you optimize Apex code to stay within CPU time limits.
Remove inefficient loops, minimize SOQL/DML calls, leverage asynchronous processing, and cache
reusable data.

6. How do you handle large data volumes in Salesforce while respecting governor limits?
Use Batch Apex, Queueable Apex, or scheduled Apex for asynchronous bulk processing and data
partitioning.

7. What best practices do you follow when writing triggers to prevent recursive calls and
hitting limits?
Use static variables to control recursion, call helper classes, and separate logic from triggers.

8. Explain the role of Batch Apex in processing large datasets efficiently.


Batch Apex processes records in manageable chunks asynchronously, avoiding governor limit
overruns.

9. How do you monitor and debug governor limit issues during development?
Use debug logs, Limits class methods to check consumption, and Salesforce Developer Console
tools.

10. What techniques do you use to optimize SOQL queries for performance?
Use selective filters, limit fields queried, use indexed fields, avoid nested queries, and paginate
large result sets.

Change Management

1. What are the different types of Salesforce sandboxes, and when would you use each type in
a release cycle?
Developer for coding, Developer Pro for more extensive dev, Partial Copy for QA with sample data,
Full sandbox for staging and user acceptance testing.
2. How do you manage sandbox refresh schedules to minimize disruption in your
development and testing workflows?
Coordinate refresh during low activity, communicate with teams, and perform post-refresh
configuration and data setup early.

3. Can you explain the purpose of change sets and what their limitations are in deployment?
Change sets deploy metadata between related orgs without scripts, but lack automation and are
limited in complex metadata support.

4. Describe best practices for managing metadata and configuration changes across multiple
sandboxes before deploying to production.
Use source control, document changes, validate in scratch and full sandboxes, run all tests pre-
deployment, and follow deployment checklists.

5. How do you handle post-refresh tasks in sandboxes, such as masking sensitive data or
updating endpoints?
Run anonymization scripts, update workflow/email templates, reset integrations and Named
Credentials, and conduct smoke testing.

real-world Apex examples that interviewers look for.


This will cover:
Triggers (bulkified, best practices)
Classes, Batch, Queueable, Future methods
SOQL/SOSL, Dynamic SOQL
Error handling & Custom Exceptions
Test Class Example (often mandatory)
Governor Limit-safe patterns
Trigger Framework / Handler Pattern

12 Apex Code Examples for a Salesforce Developer Interview

1. Bulkified Trigger – Update Account Rating


trigger AccountTrigger on Account (before insert) {
for (Account acc : [Link]) {
if ([Link] != null && [Link] < 10000) {
[Link] = 'Cold';
}
}
}
Covers: Trigger basics, bulkification, before context.

2. Trigger – Create Task When Opportunity is Closed Won


trigger OpportunityTaskTrigger on Opportunity (after update) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : [Link]) {
if ([Link] == 'Closed Won' && [Link]([Link]).StageName != 'Closed Won') {
[Link](new Task(
Subject = 'Follow Up',
WhatId = [Link],
OwnerId = [Link],
Status = 'Not Started'
));
}
}
if (![Link]()) insert tasks;
}
Covers: After update trigger, comparing old/new values.

3. Prevent Account Deletion If Contacts Exist


trigger PreventAccountDelete on Account (before delete) {
Set<Id> accountIds = new Set<Id>();
for (Account acc : [Link]) [Link]([Link]);

Map<Id, AggregateResult> counts = new Map<Id, AggregateResult>(


[SELECT AccountId, COUNT(Id) cnt FROM Contact WHERE AccountId IN :accountIds GROUP BY AccountId]
);

for (Account acc : [Link]) {


if ([Link]([Link])) {
[Link]('Cannot delete Account with related Contacts.');
}
}
}
Covers: Before delete, validation logic, aggregate queries.

4. Update Child Contacts When Parent Account Changes


trigger UpdateContactCity on Account (after update) {
Set<Id> accountIds = new Set<Id>();
for (Account acc : [Link]) {
if ([Link] != [Link]([Link]).BillingCity) {
[Link]([Link]);
}
}
if ([Link]()) return;

List<Contact> contactsToUpdate = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds];
for (Contact con : contactsToUpdate) {
[Link] = [Link]([Link]).BillingCity;
}
update contactsToUpdate;
}
Covers: Parent-child relationship handling, bulk-safe pattern.

5. Apex Class – Apply Discount


public class DiscountCalculator {
public static void applyDiscount(List<Opportunity> oppList) {
for (Opportunity opp : oppList) {
if ([Link] > 10000) [Link] *= 0.9; // 10% discount
}
update oppList;
}
}
Covers: Static methods, reusability.

6. Batch Apex – Update Contact Email Domain


global class UpdateContactEmailDomain implements [Link]<SObject> {
global [Link] start([Link] BC) {
return [Link]('SELECT Id, Email FROM Contact WHERE Email !=
null');
}
global void execute([Link] BC, List<Contact> scope) {
for (Contact con : scope) {
if ([Link]('@[Link]')) {
[Link] = [Link]('@[Link]', '@[Link]');
}
}
update scope;
}
global void finish([Link] BC) {}
}
Covers: Batch Apex, handling large data sets.

7. Queueable Apex – Send Email


public class SendSummaryEmail implements Queueable {
public void execute(QueueableContext context) {
[Link] mail = new [Link]();
[Link](new String[]{'manager@[Link]'});
[Link]('Summary Report');
[Link]('Here is the summary report.');
[Link](new [Link][]{mail});
}
}
Covers: Async processing (Queueable).

8. Future Method – HTTP Callout


public class CalloutService {
@future(callout=true)
public static void makeCallout() {
HttpRequest req = new HttpRequest();
[Link]('[Link]
[Link]('GET');
Http http = new Http();
HttpResponse res = [Link](req);
[Link]('Response: ' + [Link]());
}
}
Covers: Future methods, integrations.

9. Custom Exception & Error Handling


Covers: Custom exception, try/catch. public class DiscountException extends Exception {}

public class DiscountService {


public static void applyDiscount(Opportunity opp) {
try {
if ([Link] == null) throw new DiscountException('Amount cannot be null');
[Link] = [Link] * 0.9;
update opp;
} catch (DiscountException e) {
[Link]('Custom Error: ' + [Link]());
}
}
}

10. Dynamic SOQL Example


public class DynamicQueryExample {
public static List<SObject> fetchData(String objectName, String whereClause) {
String query = 'SELECT Id, Name FROM ' + objectName + ' WHERE ' + whereClause;
return [Link](query);
}
}
Covers: Dynamic SOQL, used for generic utilities.

11. Trigger Handler Pattern (Best Practice)


public class AccountTriggerHandler {
public static void beforeInsert(List<Account> newAccounts) {
for (Account acc : newAccounts) {
if ([Link] < 10000) [Link] = 'Cold';
}
}
}
trigger AccountTrigger on Account (before insert) {
if ([Link] && [Link]) {
[Link]([Link]);
}
}
Covers: Trigger framework, clean architecture.

12. Test Class Example


@isTest
private class AccountTriggerTest {
@isTest
static void testAccountTrigger() {
Account acc = new Account(Name='Test Account', AnnualRevenue=5000);
insert acc;
[Link]('Cold', [Link]);
}
}
Covers: Writing test classes, assertions (mandatory for deployments).

Covers all Apex concepts (Triggers, Classes, Batch, Async, Exception handling)
Shows best practices (bulkification, handler pattern, governor limit safety)
Includes dynamic SOQL, future methods, and test class (commonly asked)
Demonstrates real business use cases (discounts, validations, parent-child updates)

list of SOQL & SOSL examples Performance optimization


• Handling governor limits
• Complex parent-child queries
• Best practices for large data sets
• Security considerations

11. SOQL Query with Formula Fields and Polymorphic Fields


List<Event> events = [
SELECT Id, Subject, [Link], [Link]
FROM Event WHERE [Link] IN ('Account','Opportunity')
];
Why important: Tests ability to work with polymorphic relationships (Who & What fields).

12. SOQL Query Using Date Literals


List<Opportunity> opps = [
SELECT Id, Name, CloseDate FROM Opportunity
WHERE CloseDate = NEXT_N_DAYS:30 AND StageName != 'Closed Won'
];
Why important: Efficient filtering using Salesforce date literals (e.g., YESTERDAY, NEXT_N_DAYS:30).
13. Security-Enforced SOQL (Spring ’23+)
List<Account> secureAccounts = [
SELECT Id, Name FROM Account
WITH SECURITY_ENFORCED
];
Why important: Demonstrates knowledge of field- and object-level security enforcement (must-know for senior
devs).

14. Using FOR UPDATE to Lock Records


List<Account> accountsToLock = [
SELECT Id, Name FROM Account WHERE Industry = 'Banking' FOR UPDATE
];
Why important: Prevents race conditions when multiple processes update the same records.

15. Relationship Query with Multiple Levels


List<Account> accounts = [
SELECT Name,
(SELECT FirstName, LastName, (SELECT Subject FROM Cases) FROM Contacts)
FROM Account LIMIT 10
];
Why important: Tests ability to work with nested subqueries (multi-level parent-child).

16. Using GROUP BY ROLLUP (Advanced Aggregation)


AggregateResult[] results = [
SELECT Industry, Type, COUNT(Id) cnt
FROM Account
GROUP BY ROLLUP(Industry, Type)
];
Why important: Shows knowledge of hierarchical aggregation (reporting-level queries).

17. Handling Large Data with Iterative Query


for (List<Account> accList : [SELECT Id, Name FROM Account WHERE Industry != null LIMIT 50000]) {
// Process records in chunks
}
Why important: Demonstrates bulk-safe processing within governor limits.

18. Asynchronous SOSL for Scalability


@future
public static void searchAndProcess(String searchTerm) {
List<List<SObject>> searchResults = [
FIND :searchTerm IN ALL FIELDS RETURNING Account(Id, Name)
];
// Process results asynchronously
}
Why important: Shows handling of SOSL in async context for large search operations.

19. Chained Dynamic SOQL (Building Query at Runtime)


String baseQuery = 'SELECT Id, Name FROM Account WHERE ';
String condition = 'Industry = \'Technology\' AND Rating = \'Hot\'';
List<Account> accounts = [Link](baseQuery + condition);
Why important: Validates understanding of dynamic query building safely.

20. Performance Consideration – Selective Queries


List<Contact> selectiveQuery = [
SELECT Id, LastName FROM Contact
WHERE LastName = :lastName
AND AccountId IN :accountIds
LIMIT 200
];
Why important: Shows understanding of selectivity, filter optimization, and avoiding non-selective queries (key
for big orgs).

Covers basic → advanced SOQL & SOSL scenarios


Includes security, performance, and bulkification best practices
Demonstrates knowledge of new Salesforce features like WITH SECURITY_ENFORCED
Shows ability to handle real-world, enterprise-scale use cases

synchronous + asynchronous Apex, best practices (handler pattern,


bulkification, recursion control), callouts, batching, scheduling, platform
events, transaction control, partial DML handling, and test coverage.

Scenario (real world)


When an Order__c is confirmed:

• mark order as confirmed and set Confirmed_Date__c

• update the related Account's Last_Order_Date__c (with FOR UPDATE lock to avoid races)

• publish a platform event for high-value orders (> ₹10,000 / 10,000)


• asynchronously call an external Inventory API to reserve stock (Queueable with callout)

• there’s a daily batch that archives old orders (partial success aware) and sends a summary email

• code follows a Trigger Handler pattern and prevents recursion

• tests include callout mocks and asynchronous behavior via [Link]()/[Link]()

1) OrderTrigger — trigger that delegates to handler


trigger OrderTrigger on Order__c (before insert, before update, after insert, after update) {

if ([Link]) {

if ([Link]) [Link]([Link]);

if ([Link]) [Link]([Link], [Link]);

if ([Link]) {

if ([Link]) [Link]([Link]);

if ([Link]) [Link]([Link], [Link]);

2) TriggerRecursionControl — prevents recursion within a transaction


public class TriggerRecursionControl {

// set of processed Order Ids (transaction-scoped)

public static Set<Id> processedOrders = new Set<Id>();

// simple flag to prevent re-entry for generic triggers

public static Boolean isRunning = false;

3) OrderTriggerHandler — trigger handler (best practice)


public class OrderTriggerHandler {

public static void beforeInsert(List<Order__c> newOrders) {

for (Order__c o : newOrders) {

// default status if not provided

if ([Link](o.Status__c)) o.Status__c = 'Draft';

// mark high value

o.High_Value__c = (o.Total_Amount__c != null && o.Total_Amount__c > 10000);

}
public static void beforeUpdate(List<Order__c> newOrders, Map<Id, Order__c> oldMap) {

// ensure no null pointer and recompute high value if amount changed

for (Order__c o : newOrders) {

Order__c oldO = [Link]([Link]);

if (oldO != null && oldO.Total_Amount__c != o.Total_Amount__c) {

o.High_Value__c = (o.Total_Amount__c != null && o.Total_Amount__c > 10000);

public static void afterInsert(List<Order__c> newOrders) {

// After insert - process confirmed orders

List<Id> toProcess = new List<Id>();

for (Order__c o : newOrders) {

if (o.Status__c == 'Confirmed') [Link]([Link]);

if (![Link]()) [Link](toProcess);

public static void afterUpdate(List<Order__c> newOrders, Map<Id, Order__c> oldMap) {

if ([Link]) return;

[Link] = true;

List<Id> newlyConfirmed = new List<Id>();

for (Order__c o : newOrders) {

Order__c oldO = [Link]([Link]);

if (oldO != null && oldO.Status__c != 'Confirmed' && o.Status__c == 'Confirmed') {

[Link]([Link]);

if (![Link]()) {

[Link](newlyConfirmed);

[Link] = false;

}
4) OrderService — core business logic (sync updates + event publishing +
queueing)
public class OrderService {

public class OrderProcessingResult {

public Id orderId;

public Boolean success;

public String message;

public OrderProcessingResult(Id id, Boolean ok, String msg) {

[Link] = id; [Link] = ok; [Link] = msg;

public static void processConfirmedOrders(List<Id> orderIds) {

if ([Link]()) return;

// Protect against reprocessing in same transaction

Set<Id> toProcess = new Set<Id>();

for (Id oid : orderIds) {

if (![Link](oid)) {

[Link](oid);

[Link](oid);

if ([Link]()) return;

// Query orders with security enforced (demonstrates WITH SECURITY_ENFORCED)

List<Order__c> orders = [SELECT Id, Name, Account__c, Total_Amount__c, High_Value__c

FROM Order__c

WHERE Id IN :toProcess

WITH SECURITY_ENFORCED];

// Update account last order date using FOR UPDATE (locks to avoid concurrent updates)

Set<Id> acctIds = new Set<Id>();

for (Order__c o : orders) if (o.Account__c != null) [Link](o.Account__c);


if (![Link]()) {

List<Account> accounts = [SELECT Id, Last_Order_Date__c FROM Account WHERE Id IN :acctIds FOR UPDATE];

Map<Id, Account> acctMap = new Map<Id, Account>(accounts);

for (Order__c o : orders) {

if (o.Account__c != null && [Link](o.Account__c)) {

[Link](o.Account__c).Last_Order_Date__c = [Link]();

// Savepoint usage to rollback account update if something goes wrong further in process

Savepoint sp = [Link]();

try {

update accounts;

} catch (Exception ex) {

[Link](sp);

// Log and continue: don't block posting platform events or async calls for other orders

[Link]('Account update failed: ' + [Link]());

// Publish platform event for high-value orders and collect for async sync

List<Id> ordersNeedingInventorySync = new List<Id>();

for (Order__c o : orders) {

if (o.High_Value__c == true) {

High_Value_Order_Event__e evt = new High_Value_Order_Event__e(

OrderId__c = [Link]([Link]),

Amount__c = o.Total_Amount__c,

AccountId__c = [Link](o.Account__c)

);

[Link](evt);

[Link]([Link]);

// Enqueue a single Queueable job to sync inventory for these orders (batch them)

if (![Link]()) {

// pass the ids to queueable job


[Link](new InventorySyncQueueable(ordersNeedingInventorySync));

// Example: dynamic SOQL utility to get top N products sold (illustrates aggregate & dynamic)

public static List<AggregateResult> getTopProducts(Integer topN) {

if (topN == null || topN <= 0) topN = 5;

String q = 'SELECT Product__c, COUNT(Id) totalSold FROM Order_Line_Item__c GROUP BY Product__c ORDER BY
COUNT(Id) DESC LIMIT ' + topN;

return [Link](q);

// Demonstrates partial insert with allOrNone = false for Order Line Items

public static List<OrderProcessingResult> createOrderLineItems(List<Order_Line_Item__c> lines) {

List<OrderProcessingResult> results = new List<OrderProcessingResult>();

if ([Link]()) return results;

[Link][] saveResults = [Link](lines, false);

for (Integer i = 0; i < [Link](); i++) {

if (saveResults[i].isSuccess()) {

[Link](new OrderProcessingResult(lines[i].Order__c, true, 'Inserted line id: ' + saveResults[i].getId()));

} else {

[Link](new OrderProcessingResult(lines[i].Order__c, false, saveResults[i].getErrors()[0].getMessage()));

return results;

5) InventorySyncQueueable — Queueable with callout to external Inventory


API
public class InventorySyncQueueable implements Queueable, [Link] {

private List<Id> orderIds;

public InventorySyncQueueable(List<Id> orderIds) {

[Link] = orderIds != null ? orderIds : new List<Id>();

public void execute(QueueableContext qc) {

if ([Link]()) return;

// Query order and lineitems in bulk

List<Order__c> ords = [SELECT Id, Name, Total_Amount__c, Account__c FROM Order__c WHERE Id IN :orderIds];

Map<Id, List<Order_Line_Item__c>> lineMap = new Map<Id, List<Order_Line_Item__c>>();

for (Order_Line_Item__c li : [SELECT Id, Order__c, Product__c, Quantity__c FROM Order_Line_Item__c WHERE Order__c IN :orderIds]) {

if (![Link](li.Order__c)) [Link](li.Order__c, new List<Order_Line_Item__c>());

[Link](li.Order__c).add(li);

// Build JSON payload

List<Map<String, Object>> payloadOrders = new List<Map<String,Object>>();

for (Order__c o : ords) {

Map<String, Object> p = new Map<String, Object>{

'orderId' => [Link],

'total' => o.Total_Amount__c,

'lines' => new List<Object>()

};

if ([Link]([Link])) {

for (Order_Line_Item__c li : [Link]([Link])) {

[Link]('lines').add(new Map<String, Object>{

'product' => li.Product__c,

'qty' => li.Quantity__c

});

[Link](p);

String jsonBody = [Link](payloadOrders);

// Call external API (use Named Credential in real org; here we demonstrate manual callout)

HttpRequest req = new HttpRequest();

// NOTE: replace endpoint with Named Credential or remote site setting in production

[Link]('[Link]
[Link]('POST');

[Link]('Content-Type', 'application/json');

[Link](jsonBody);

Http http = new Http();

try {

HttpResponse res = [Link](req);

if ([Link]() >= 200 && [Link]() < 300) {

[Link]('Inventory reserved for orders: ' + orderIds);

} else {

[Link]('Inventory sync failed: ' + [Link]());

// you might create an error record, platform event, or queue a retry job here

} catch (Exception ex) {

[Link]('Callout failed: ' + [Link]());

// Consider queuing a retry or writing to an error queue

6) OrderBatchArchive — Batch job to archive old orders with partial-success


logging
global class OrderBatchArchive implements [Link]<SObject>, [Link] {

global [Link] start([Link] BC) {

// archive orders older than 365 days

return [Link]('SELECT Id, Status__c, LastModifiedDate FROM Order__c WHERE LastModifiedDate <
LAST_N_DAYS:365 AND Status__c != \'Archived\'');

global void execute([Link] BC, List<Order__c> scope) {

for (Order__c o : scope) {

o.Status__c = 'Archived';

// partial success handling

[Link][] res = [Link](scope, false);

for (Integer i = 0; i < [Link](); i++) {

if (!res[i].isSuccess()) {

[Link]('Failed to archive Order Id: ' + scope[i].Id + ' Error: ' + res[i].getErrors()[0].getMessage());

}
}

global void finish([Link] BC) {

// send summary email or log completion

[Link] mail = new [Link]();

[Link](new String[]{'ops@[Link]'});

[Link]('OrderArchive Batch Finished');

[Link]('Order archiving completed. Check debug logs for details.');

[Link](new [Link][]{mail});

7) DailyBatchScheduler — schedules the batch daily


global class DailyBatchScheduler implements Schedulable {

global void execute(SchedulableContext sc) {

[Link](new OrderBatchArchive(), 200);

// Example scheduling snippet (run once from anonymous):

// [Link]('Daily Order Archive', '0 0 0 * * ?', new DailyBatchScheduler());

8) OrderProcessingException — custom exception example

public class OrderProcessingException extends Exception {}

9) InventoryCalloutMock — HttpCalloutMock for tests


@isTest

global class InventoryCalloutMock implements HttpCalloutMock {

global HTTPResponse respond(HTTPRequest req) {

HttpResponse res = new HttpResponse();

// Make a fake success response

[Link]('Content-Type', 'application/json');
[Link]('{"status":"success","reserved":true}');

[Link](200);

return res;

10) OrderTriggerTest — tests triggers, queueable callout and platform event


publishing
@isTest
private class OrderTriggerTest {
@isTest static void testOrderConfirmProcessing() {
// Prepare data
Account acct = new Account(Name='Test Acct');
insert acct;

// Create order in Draft


Order__c ord = new Order__c(Name='O-1001', Account__c = [Link], Total_Amount__c =
15000, Status__c = 'Draft');
insert ord;

// Set mock for callouts


[Link]([Link], new InventoryCalloutMock());

// Confirm the order to trigger processing


ord.Status__c = 'Confirmed';
[Link]();
update ord; // triggers OrderService ->
[Link](InventorySyncQueueable)
[Link]();

// Verify account last order date updated


acct = [SELECT Last_Order_Date__c FROM Account WHERE Id = :[Link]];
[Link]([Link](), acct.Last_Order_Date__c, 'Account Last Order Date
should be today');

// Also test batch and archiving


// create old order
Order__c oldOrd = new Order__c(Name='OldOrder', Status__c='Confirmed',
Total_Amount__c = 50);
insert oldOrd;

// Manipulate LastModifiedDate in tests isn't trivial; instead simulate by calling


batch start with query that picks some record.
[Link]();
[Link](new OrderBatchArchive(), 200);
[Link]();
}

@isTest static void testCreateOrderLineItemsPartialInsert() {


// create order
Account a = new Account(Name='LineTestAcct'); insert a;
Order__c o = new Order__c(Name='LineParent', Account__c = [Link], Total_Amount__c =
100); insert o;

List<Order_Line_Item__c> lines = new List<Order_Line_Item__c>();


// valid line
[Link](new Order_Line_Item__c(Order__c = [Link], Product__c = 'P1', Quantity__c =
1));
// invalid line (missing required Product__c example), emulate by leaving
Product__c null if it's required in org
[Link](new Order_Line_Item__c(Order__c = [Link], Quantity__c = 2));

List<[Link]> res =
[Link](lines);
// one success, one failure (expected)
Integer successCount = 0;
for ([Link] r : res) if ([Link]) successCount++;
[Link](successCount >= 0, 'At least zero success, this test shows partial
insert handling');
}
}

Explanations & important interviewer talking points

• Trigger Handler Pattern: OrderTrigger delegates to OrderTriggerHandler. This makes logic testable, maintainable,
and prevents multi-branch spaghetti in triggers.

• Recursion Prevention: [Link] + isRunning prevent re-processing same record


inside the same transaction (static variables are transaction-scoped).

• FOR UPDATE: We lock Account records with FOR UPDATE when updating Last_Order_Date__c to avoid concurrency
problems when many orders confirm at once.

• WITH SECURITY_ENFORCED: Used to enforce field & object-level security in queries (good for managed packages or
to avoid leaking data).

• Asynchronous Processing: InventorySyncQueueable is used for callouts and background processing. It implements
[Link].

• Callout Mocking in Tests: InventoryCalloutMock and [Link] allow testing queueable callouts. Wrap
[Link]() operations in [Link]()/[Link]() to execute async in tests.

• Batch with Partial Success: [Link](scope, false) allows partial successes; we iterate [Link][]
to log or handle errors.

• Savepoint & Rollback: When updating Accounts, we use a Savepoint and [Link] to avoid leaving accounts
in partial inconsistent states if something else fails.

• Platform Events: Publishing High_Value_Order_Event__e demonstrates event-driven architecture; other systems can
subscribe to react to high-value orders asynchronously.

• Partial DML & Error Handling: [Link]() uses [Link](..., false) and returns
detailed OrderProcessingResult objects so caller can decide next steps, retries, or user messages.

• Dynamic SOQL & Aggregates: getTopProducts() shows dynamic query building for aggregate results; useful for
dashboards and ad-hoc reporting.

• Test Coverage: Tests exercise trigger logic, queueable callouts, batch execution, and partial DML. Use
[Link]()/[Link]() for async behavior.

How to adapt this to your org


• Replace custom object/field API names (e.g., Order__c, Order_Line_Item__c, High_Value_Order_Event__e) with your
org's real names.

• Use Named Credentials for external endpoints (safer than hard-coded endpoints), and put endpoint in
[Link]('callout:My_Named_Cred').

• Add retry logic (exponential backoff) if inventory callouts fail frequently — you can store failed order ids in a custom
object and have a scheduled retry job.

• Add custom metadata to store thresholds (e.g., high value = 10000) rather than hard-coding.

15 Real-Scenario Salesforce Flow Interview Questions

But for 5+ years of experience, interviewers also expect you to:

• Show best practices (Fault Paths, Subflows, Bulkification in Flows)

• Handle complex business scenarios (Multi-object updates, Approval integration, Error handling)

• Cover newer Flow features (MFA screen components, Reactive screen components, HTTP callouts from Flow,
Migrate from Workflow/Process Builder)

1. Screen Flow – Expense Submission with Conditional Approval

Best Practice: Use Fault Paths on Create/Update elements to capture errors and display them to user.

2. Record-Triggered Flow – Lead Assignment by Region


Best Practice: Use Assignment Element instead of Update directly inside Loop for better bulkification.

3. Platform Event Flow – Notify Users on Critical Data Change

Key Point: Platform Event Flow runs asynchronously → no transaction lock issues .

4. Screen Flow – Dynamic Navigation Based on User Input

Best Practice: Use Reactive Screens to dynamically show/hide components without extra screens.

5. Record-Triggered Flow – Update Contacts When Account Changes


Best Practice: Use One Update Element after Loop (not inside loop) to avoid hitting DML limits.

6. Scheduled Flow – Nightly Cleanup

Key Point: Use Scheduled Flows for soft delete/archive tasks without Apex.

7. Screen Flow – Capture Feedback with Branching

Key Point: Use Fault Paths for Case creation failures and show friendly error message.
8. Platform Event Flow – Real-Time Inventory Update
Platform Event Raised: New Order Placed

Get Related Product Inventory

Assignment: Reduce Stock Quantity = OrderedQty

Update Product Records

Decision: Stock < Reorder Level?

Yes

Send Reorder Email to Procurement

End
Key Point: This prevents overselling and triggers restocking automatically.

9. Record-Triggered Flow – Auto-Close Cases After Inactivity


Case Updated

Formula: Days_Since_Last_Update__c

Decision: Days > 7 AND Status != 'Closed'?

Yes

Update Case Status = 'Closed'

Send Closure Notification

End
Best Practice: Always include Decision to prevent unwanted updates.

10. Screen Flow – Multi-Step Employee Onboarding


Start

Screen 1: Personal Info

Validation Rules (Custom)

Screen 2: Job Info

Screen 3: Equipment Request

Create Employee Record + Related Equipment Requests

Send Welcome Email

End
Key Point: Use Subflows for equipment provisioning → keeps flow modular.

11. Record-Triggered Flow – Cross-Object Update with Error Handling


Opportunity Updated (Stage = Closed Won)

Get Related Account

Assignment: Update Account.Status__c = 'Customer'

Update Account

Fault Path → Create Error Log Record

End
Best Practice: Use Fault Paths to capture update failures → store them in custom Log object for admin review.

12. Record-Triggered Flow – Create Task and Send Notification


Case Created (Priority = High)

Create Task (Follow-up)

Send In-App Notification to Case Owner

End
Key Point: Combine Task creation + Notification → improves user productivity.

13. Platform Event Flow – Handle Third-Party Payment Response


Platform Event Received: Payment_Processed__e

Get Related Opportunity/Invoice

Decision: Payment Status = 'Success'?
↓ ↓
Yes No
↓ ↓
Update Status Paid Update Status Failed

Send Email to Customer

End
Key Point: Ideal for asynchronous payment processing scenarios.

14. Record-Triggered Flow – Auto-Create Renewal Opportunity


Contract End Date = Today

Create Renewal Opportunity (CloseDate = EndDate + 30 days)

Send Email to Sales Team

End
Key Point: Automates renewal pipeline, ensures no missed contracts.

15. Screen Flow – User-Driven Case Escalation


Start

Screen: Select Case to Escalate

Decision: Case Priority Already High?

Yes → Show Message "Already Escalated" → End
No

Update [Link] = 'High'

Send Notification to Support Manager

End
Best Practice: Use Dynamic Record Choice in Screen Flow to allow user to pick cases
dynamically.

Now This is a Rock-Solid 5-Year Experience Flow Question Bank


You have:

Screen Flows (User Interaction, Conditional, Multi-Step)

Record-Triggered Flows (Bulk-safe, Cross-object Updates)

Platform Event Flows (Async Event-driven)

Scheduled Flows (Nightly Jobs)

Error Handling, Subflows, Notifications

Realistic Business Use Cases

This level of coverage will impress interviewers because it shows:


You know flow design patterns
You understand bulkification and governor limits
You can handle complex business logic without Apex

You might also like