Top 100 Salesforce Interview Questions Asked at TCS 2026 | Apex, LWC, SOQL & Scenarios
🏢 TCS Salesforce Interview Prep 2026
Salesforce Interview Questions
Asked at TCS 2026
Asked at TCS 2026
100 real Salesforce interview questions asked at Tata Consultancy Services (TCS) — Apex, LWC, SOQL, Security, Flows & Scenarios. Built from actual candidate experiences on Glassdoor, LinkedIn & Ambitionbox. 100% Free.
100
Questions
8
Topics
2
Rounds Covered
100%
Free
🏢 TCS Salesforce Interview Facts
⏱️
Process Duration
1-2 weeks avg
😊
Positive Experience
69.5% positive
⭐
Difficulty
Easy-Medium (2.92/5)
🎯
Focus
Fundamentals + Hands-on
📋 TCS Interview Process (2 Rounds)
R1
Technical Round — TR (45-60 mins)
Apex triggers, governor limits, SOQL, LWC, security model, object relationships, Flows, deployment. Hands-on coding on Apex. Real-time scenario questions.
R2
Manager Round — MR (30-45 mins)
Project experience, problem-solving approach, behavioral questions, Salesforce architecture decisions, team collaboration scenarios.
R3
HR Round (if applicable)
Salary discussion, notice period, cultural fit, career goals. Not always present for experienced candidates.
💡 TCS-Specific Interview Tips
🎯
Fundamentals first — TCS focuses heavily on basics. Know your OWD, profiles, roles, triggers, and governor limits inside out.
💻
Hands-on Apex — Write triggers and basic Apex code by hand. TCS specifically asks hands-on coding questions in the technical round.
🔄
Know Flows — Record-triggered Flows have replaced Workflow Rules. TCS asks about modern automation heavily.
📚
Project-based answers — Always relate answers to real project experience. TCS interviewers love "In my project, I did..."
🔒
Security model end-to-end — OWD, profiles, permission sets, roles, sharing rules. This comes up in every TCS round.
📋 Topics Covered — 100 Questions
🔗 More Company-Wise Interview Prep
☁️ Section 1 — Salesforce Fundamentals
Q1–Q15 · Basic → Intermediate · Most Asked in TCS Technical Round
Q1
What is Salesforce and what makes it different from traditional CRM?
✅ Direct Answer
Salesforce is the world's #1 cloud-based CRM platform built on multi-tenant architecture — all customers share the same infrastructure while data remains isolated. Unlike traditional on-premise CRM, Salesforce requires no hardware, auto-updates 3x per year, is accessible anywhere, and scales instantly. It's SaaS — Software as a Service.
💡 Why?
Multi-tenancy means Salesforce maintains one codebase for thousands of customers — reducing cost and enabling automatic upgrades. Governor limits exist because of multi-tenancy — preventing one org from monopolizing shared resources. This is why TCS asks this question — it shows you understand the platform's foundation.
🌍 Real World Example
At XYZ Company, we moved from on-premise Siebel CRM to Salesforce. Old system: expensive servers, manual upgrades every 2 years, no mobile access, IT team of 10 to maintain. Salesforce: zero hardware, 3 automatic upgrades per year, mobile app out of the box, admin team of 2. Total cost reduced by 60% in year 1.
🔑 Key Points for Interviewer
- Multi-tenant: shared infrastructure, isolated data
- SaaS: no hardware, subscription model, auto-updates
- 3 releases per year: Spring, Summer, Winter
- Governor limits: protect shared resources in multi-tenant environment
- AppExchange: 6,000+ pre-built solutions marketplace
🎤 One-Line Answer
"Salesforce is a cloud-based multi-tenant CRM — no hardware, auto-updates 3x/year, accessed anywhere. Governor limits protect the shared infrastructure from any single org monopolizing resources."
Q2
What is the Salesforce order of execution?
✅ Direct Answer
On record save: 1) System Validation 2) Before-save Flows 3) Before Triggers 4) Custom Validation Rules 5) Duplicate Rules 6) After Triggers 7) Assignment/Auto-response/Workflow Rules 8) After-save Flows 9) Roll-up Summary recalculation 10) Criteria-based Sharing 11) Commit to database.
🌍 Real World Example
Bug at XYZ Company: validation rule failing even though trigger should set the required field. Root cause: Before-save Flow was overwriting trigger's value (Flow runs BEFORE triggers now). Fix: removed conflicting Flow assignment. Without knowing order of execution, this took 2 hours to debug. With this knowledge: 10 minutes.
🔑 Key Points for Interviewer
- Before-save Flow runs BEFORE before triggers — new important behavior
- Validation rules fire AFTER before triggers — triggers can satisfy validation
- After triggers fire before workflow rules
- Roll-up summary recalculation happens post-commit
- TCS asks this in almost every Salesforce technical round
🎤 One-Line Answer
"Order: System Validation → Before-save Flow → Before Trigger → Validation Rules → After Trigger → Workflow → After-save Flow → Commit. Before-save Flows now run BEFORE before triggers — critical to know."
Q3
What are governor limits in Salesforce? Name the most important ones.
✅ Direct Answer
Governor limits cap resource usage per transaction in multi-tenant environment. Most critical: 100 SOQL queries per sync transaction, 150 DML statements, 10,000 DML rows, 6 MB heap size, 10,000 ms CPU time. Async context doubles most limits (200 SOQL, 12 MB heap, 60,000 ms CPU).
🌍 Real World Example
Developer wrote SOQL inside a for loop — 200 records × 1 SOQL = 200 queries. Error: "Too many SOQL queries: 101." Fix: moved SOQL outside loop, used Map for lookups. This is the #1 hands-on question TCS asks — write a bulkified trigger that avoids this error.
🔑 Key Points for Interviewer
- SOQL: 100 sync / 200 async
- DML: 150 statements / 10,000 rows
- Heap: 6 MB sync / 12 MB async
- CPU: 10,000 ms sync / 60,000 ms async
- Solution: bulkify — never SOQL/DML inside loops
🎤 One-Line Answer
"Governor limits protect multi-tenant platform — 100 SOQL, 150 DML, 6 MB heap per transaction. Solution: bulkification — move all queries and DML outside loops, process collections."
Q4
What is the difference between master-detail and lookup relationships?
✅ Direct Answer
Master-Detail: tight coupling — child cannot exist without parent, inherits parent's sharing, supports roll-up summary fields, cascade delete. Lookup: loose coupling — child can exist without parent, independent sharing, no roll-up summary, no cascade delete by default.
🌍 Real World Example
Order_Line_Item__c to Order__c: Master-Detail (line item has no meaning without order — roll-up total, cascade delete). Contact to Account: Lookup (contact can exist without employer). TCS specifically asks: "When would you use Master-Detail over Lookup?" — answer: when child record has no meaning without parent and you need roll-up summaries.
🔑 Key Points for Interviewer
- Master-Detail: roll-up summary, cascade delete, inherited sharing, required parent
- Lookup: no roll-up, optional parent, independent sharing
- Junction Object: two Master-Details = many-to-many
- Max 2 Master-Detail relationships per object
- Can convert Lookup → Master-Detail only if no null values exist
🎤 One-Line Answer
"Master-Detail: roll-up summary, cascade delete, required parent. Lookup: optional parent, independent sharing. Choose Master-Detail when child has no meaning without parent and you need roll-up aggregations."
Q5
What is a junction object and when do you use it?
✅ Direct Answer
A junction object has two Master-Detail relationships to create a many-to-many relationship between two objects. Example: Student__c and Course__c have a many-to-many relationship — Enrollment__c is the junction object with Master-Detail to both. It can also store attributes about the relationship (enrollment date, grade).
🌍 Real World Example
At XYZ Company: Product__c (many) ↔ Campaign__c (many). Created Campaign_Product__c junction: MD to Product + MD to Campaign. Added fields: Discount__c, Featured__c, Start_Date__c. Reports on Campaign_Product__c show full product-campaign relationship with discount details. TCS loves this question — always explain with a clear real example.
🔑 Key Points for Interviewer
- Exactly 2 Master-Detail relationships required
- Inherits sharing from both parents — most restrictive applies
- Can store attributes about the relationship itself
- Uses both Master-Detail slots — no room for a 3rd
- Reports can be built on junction objects for full many-to-many visibility
🎤 One-Line Answer
"Junction object has two Master-Detail relationships creating many-to-many — can also store attributes about the relationship like enrollment date, grade, or discount percentage."
Q6
What are the different types of sandboxes in Salesforce?
✅ Direct Answer
Developer (5 MB, refresh anytime — individual dev). Developer Pro (1 GB, refresh anytime). Partial Copy (5 GB with sample production data, refresh 5 days — QA/UAT). Full (complete production copy, refresh 29 days — pre-production). Scratch Org (SFDX — temporary, disposable, source-driven).
🌍 Real World Example
TCS project sandbox strategy: 5 Developer sandboxes (individual devs), 1 Integration sandbox (daily code merges), 1 QA Partial Copy (realistic data), 1 UAT Full sandbox (exact production copy for client testing), 1 Pre-Prod Full (final check). Changes flow: Dev → Integration → QA → UAT → Pre-Prod → Production.
🔑 Key Points for Interviewer
- Developer: free, 5 MB, individual, refresh anytime
- Partial Copy: includes production data sample — realistic testing
- Full: exact production copy — most expensive, slowest refresh (29 days)
- Scratch Orgs: SFDX, temporary, disposable — modern DevOps approach
- TCS uses all sandbox types on enterprise projects
🎤 One-Line Answer
"Four sandbox types: Developer (5 MB), Developer Pro (1 GB), Partial Copy (5 GB sample data), Full (complete production copy) — each for different stages of SDLC from development to pre-production testing."
Q7
What is Custom Metadata Type vs Custom Settings?
✅ Direct Answer
Custom Metadata Types (CMT): deployment-ready config — records deploy with Change Sets and packages, usable in formulas and validation rules, no SOQL governor limit to read. Custom Settings: org-specific config — not deployable with packages, requires SOQL or Settings API, supports hierarchy (org/profile/user level).
🌍 Real World Example
API endpoint URLs stored in CMT — deploy once, correct URL automatically in every sandbox and production. If stored in Custom Settings: manually reconfigure in every sandbox after refresh. CMT saves 2+ hours of post-deployment setup. TCS asks this to check if you know modern Salesforce configuration patterns.
🔑 Key Points for Interviewer
- CMT (__mdt): deployable, usable in formulas, no governor limit reads
- Custom Settings (__c): hierarchy support, not deployable, SOQL to read
- CMT for: API endpoints, thresholds, feature flags, mapping tables
- Custom Settings for: user/profile-specific hierarchy values
- Modern Salesforce: CMTs preferred for all deployable configuration
🎤 One-Line Answer
"Custom Metadata deploys with code and works in formulas. Custom Settings are org-specific and don't deploy. Use CMTs for any configuration that needs to travel automatically between environments."
Q8
What is a Platform Event in Salesforce?
✅ Direct Answer
Platform Events implement publish-subscribe messaging — publishers send events via EventBus.publish(); subscribers (Apex triggers on the event, Flows, or external systems via CometD) react independently. Events are decoupled — publisher doesn't know or care who subscribes. Used for real-time integrations, LWC notifications, and async processing.
🌍 Real World Example
Order confirmation: Order trigger publishes Order_Placed__e. Multiple subscribers: 1) Apex trigger creates fulfillment records 2) LWC shows real-time notification 3) MuleSoft receives via CometD and triggers ERP. Publisher knows nothing about any of them — fully decoupled. If ERP is down, events queue and replay when it recovers.
🔑 Key Points for Interviewer
- Platform Event objects end in __e
- EventBus.publish() to fire; triggers on __e to subscribe
- Decoupled: publisher and subscriber are independent
- ReplayId: replay missed events up to 72 hours
- CDC (Change Data Capture): Salesforce-generated events for record changes
🎤 One-Line Answer
"Platform Events enable publish-subscribe messaging — publisher fires event, multiple independent subscribers react. Fully decoupled, supports replay up to 72 hours, used for real-time integrations and async processing."
Q9
What is a roll-up summary field and what are its limitations?
✅ Direct Answer
Roll-up summary aggregates child record data (COUNT, SUM, MIN, MAX) onto a master record in Master-Detail relationship. Limitations: only on Master-Detail parent (not Lookup), max 25 per object, can cause performance issues on high-volume orgs, no cross-filter conditions on non-standard fields.
🌍 Real World Example
Total_Order_Value__c on Order__c = SUM(Amount__c) from all Order_Line_Item__c. Limitation hit: needed roll-up on Lookup relationship (Contact → Account). Solution: DLRS (Declarative Lookup Rollup Summaries) AppExchange package — extends roll-up to Lookup relationships without code.
🔑 Key Points for Interviewer
- Functions: COUNT, SUM, MIN, MAX with optional filter criteria
- Only on Master-Detail parent — not Lookup
- For Lookup: use DLRS package or Apex trigger
- Max 25 roll-up summary fields per object
- Performance impact on high-volume orgs — test with realistic data
🎤 One-Line Answer
"Roll-up summary (COUNT/SUM/MIN/MAX) aggregates child onto master — only on Master-Detail, not Lookup. Max 25 per object. Use DLRS package for roll-ups on Lookup relationships."
Q10
What is the difference between a Workflow Rule and a Flow?
✅ Direct Answer
Workflow Rules are officially retired (2025). Flows are the modern replacement — they do everything workflow rules did plus much more: multi-object updates, loops, subflows, complex logic, screen interactions. All new automation must be in Flows. Existing Workflow Rules should be migrated using Salesforce's "Migrate to Flow" tool.
🌍 Real World Example
Old Workflow Rule: send email when Opportunity Stage = Closed Won. New Record-Triggered Flow: when Stage changes to Closed Won → update related Contacts → create 5 onboarding Tasks → send email → create renewal Opportunity for 12 months later. One Flow replaces 3 separate workflow rules and does more. TCS will ask about this migration — be ready.
🔑 Key Points for Interviewer
- Workflow Rules: retired 2025 — no new creation allowed
- Process Builder: also retiring — migrate to Flow
- Migrate to Flow tool: Setup → Migrate to Flow
- Flow types: Record-Triggered, Screen, Scheduled, Auto-launched
- Flows: more powerful, more maintainable, strategic direction
🎤 One-Line Answer
"Workflow Rules are retired — Flows replace them entirely. Use Record-Triggered Flows for all new automation. Migrate existing workflows using Salesforce's built-in 'Migrate to Flow' tool."
Q11
What is a Record Type in Salesforce?
✅ Direct Answer
Record Types allow different page layouts, picklist values, and business processes for different user profiles on the same object — without creating separate objects. A Case can have "Technical Support" Record Type (technical fields, SLA picklist) and "Billing Inquiry" Record Type (billing fields, different picklists) — same object, different experiences.
🌍 Real World Example
XYZ Company Lead object: "Web Lead" Record Type (shows web source fields, marketing picklists) vs "Trade Show Lead" Record Type (shows event fields, booth number, different qualification stages). Same Lead object, different layouts and picklist values per source. Profiles control which Record Types each team can create.
🔑 Key Points for Interviewer
- Controls: page layout, picklist values, business process per profile
- Profile assignment: which Record Types a profile can create
- Default Record Type: assigned when no selection needed
- SOQL: WHERE RecordType.Name = 'Technical Support'
- Avoid too many Record Types — creates maintenance complexity
🎤 One-Line Answer
"Record Types enable different page layouts and picklist values per profile on one object — use for genuinely different business processes. Avoid when simple field visibility rules would suffice."
Q12
What is the difference between a profile and a permission set?
✅ Direct Answer
Profile: mandatory, exactly one per user, defines baseline permissions (object CRUD, field access, system permissions, login hours). Permission Set: optional, multiple per user, extends additional permissions on top of profile. Best practice: minimum-access profile + permission sets for specific access. Salesforce is retiring permissions from profiles — future is permission sets only.
🔑 Key Points for Interviewer
- Profile: 1 per user, required, baseline
- Permission Set: multiple per user, optional, extends access
- Permission Set Groups: bundle multiple PSets for job function
- Salesforce retiring profile permissions — PSets are the future
- Modern approach: minimum-access profile + permission sets
🎤 One-Line Answer
"Profile = mandatory baseline (1 per user). Permission Set = optional extension (multiple per user). Best practice: minimum-access profile + permission sets. Salesforce is retiring profile permissions in favor of PSets."
Q13
What is an External ID in Salesforce and why is it important?
✅ Direct Answer
External ID is a custom field marked as External ID — stores unique identifier from an external system, gets auto-indexed (making queries selective), and enables upsert operations matching records by external key instead of Salesforce ID. Critical for data migrations and integrations where Salesforce IDs don't exist in the source system.
🌍 Real World Example
SAP → Salesforce migration: SAP has Customer_Number (CUST-12345). Upsert Accounts by SAP_Customer_Number__c (External ID) — if match exists, update; if not, insert. Then upsert Contacts referencing Account by SAP_Customer_Number without knowing Salesforce IDs. All relationships maintained in one pass without knowing Salesforce record IDs.
🔑 Key Points for Interviewer
- Auto-indexed — selective SOQL queries
- Enables upsert — insert or update by external key
- Up to 25 External ID fields per object
- Essential for all data migrations and integrations
- Cross-object reference: relate child to parent by parent's External ID in Data Loader
🎤 One-Line Answer
"External ID stores source system's key, gets auto-indexed, enables upsert without knowing Salesforce IDs — essential for data migrations and integrations where source system identifiers must be preserved."
Q14
What is the difference between Data Loader and Data Import Wizard?
✅ Direct Answer
Data Import Wizard: browser-based, max 50,000 records, limited standard + custom objects, no delete. Data Loader: desktop/CLI app, millions of records, all objects, all DML operations (Insert/Update/Upsert/Delete/Hard Delete), schedulable via command line, uses Bulk API 2.0.
🔑 Key Points for Interviewer
- Data Import Wizard: 50K limit, browser, limited objects, no delete
- Data Loader: unlimited records, desktop/CLI, all objects, all DML
- Data Loader uses Bulk API 2.0 for large volumes
- External IDs: required for upsert in Data Loader
- TCS uses Data Loader for all data migrations
🎤 One-Line Answer
"Data Import Wizard: 50K limit, browser, easy for admins. Data Loader: millions of records, all objects, all DML operations — use Loader for large data migrations and automated scheduled loads."
Q15
What is the difference between Declarative and Programmatic development in Salesforce?
✅ Direct Answer
Declarative: point-and-click — no code required (Flows, Validation Rules, Process Builder, Reports, Record Types). Faster to build, admin-maintainable, no deployment complexity. Programmatic: code-based — Apex, LWC, Visualforce, SOQL. More powerful and flexible but requires developer skills and proper testing/deployment. TCS golden rule: declarative first, programmatic only when declarative can't handle it.
🔑 Key Points for Interviewer
- Declarative: Flows, Validation Rules, Reports, Record Types, Page Layouts
- Programmatic: Apex, LWC, Visualforce, SOQL, REST API
- Best practice: declarative first — less maintenance, less risk
- Programmatic for: complex logic, callouts, batch processing, custom UI
- TCS expects candidates to know WHEN to use each approach
🎤 One-Line Answer
"Declarative = no-code (Flows, Validation Rules, Reports) — fast, admin-maintainable. Programmatic = code (Apex, LWC) — more powerful. Always try declarative first; use programmatic only when declarative genuinely can't handle the requirement."
🔒 Section 2 — Security & Sharing Model
Q16–Q25 · Intermediate · Asked in Every TCS Round
Q16
Explain the Salesforce security model — OWD, Role Hierarchy, Sharing Rules, Manual Sharing.
✅ Direct Answer
Four layers: OWD (most restrictive baseline — Private, Public Read Only, Public Read/Write). Role Hierarchy (managers automatically see their team's records). Sharing Rules (extend access beyond OWD for groups/roles). Manual Sharing (individual record sharing by owner). Each layer can only OPEN access — never restrict beyond OWD.
🌍 Real World Example
Opportunity OWD = Private. Role Hierarchy: Sales Manager sees their reps' opportunities. Sharing Rule: share all Opportunities tagged "Enterprise" with Enterprise Sales public group. Manual Sharing: rep shares one confidential deal with Legal for contract review. All four layers work together — OWD is the floor, each layer opens access further.
🔑 Key Points for Interviewer
- OWD = most restrictive starting point — build up from here
- Role Hierarchy: data VISIBILITY not permissions (what you SEE not what you DO)
- Sharing Rules: criteria-based or owner-based, max 300 per object
- Manual Sharing: one record at a time, doesn't persist on owner change
- Apex Managed Sharing: programmatic, persists through owner changes
🎤 One-Line Answer
"OWD (restrictive baseline) → Role Hierarchy (manager sees team) → Sharing Rules (extend to groups) → Manual Sharing (individual records) — each layer only opens access, never restricts beyond OWD."
Q17
What is the difference between object-level and record-level security?
✅ Direct Answer
Object-level (Profile/Permission Set): controls whether a user can perform CRUD on an object at all — can they see the tab, create, edit, delete records of this type? Record-level (OWD, Roles, Sharing Rules): controls which SPECIFIC records of that object the user can see. Both must be satisfied simultaneously.
🌍 Real World Example
Support Rep: Object = Read + Create Cases (profile). Record = only cases in their region (sharing rule). Without object access: record access is irrelevant — can't even see the Cases tab. Without record access: object access shows an empty list. Both must be satisfied — AND condition, not OR.
🎤 One-Line Answer
"Object-level = can you use this object at all (CRUD via Profile). Record-level = which specific records can you see (OWD + Roles + Sharing). Both must be satisfied simultaneously."
Q18
What is Field Level Security (FLS) and how do you enforce it in Apex?
✅ Direct Answer
FLS controls which fields a user can see and edit — configured per profile/permission set. Apex runs in system context by default and bypasses FLS unless explicitly enforced using WITH SECURITY_ENFORCED in SOQL, Schema.describeSObjectType checks, or stripInaccessible() method.
🌍 Real World Example
// Enforce FLS in SOQL
List<Account> accs = [SELECT Id, Name, AnnualRevenue FROM Account WITH SECURITY_ENFORCED];
// Throws exception if user doesn't have FLS on any field in SELECT
// stripInaccessible - removes inaccessible fields instead of throwing
SObjectAccessDecision dec = Security.stripInaccessible(AccessType.READABLE, accs);
List<Account> safeAccs = (List<Account>) dec.getRecords();
🔑 Key Points for Interviewer
- FLS set on profiles and permission sets per field
- WITH SECURITY_ENFORCED: throws exception if field inaccessible
- stripInaccessible(): removes inaccessible fields gracefully
- Apex default: system context — bypasses FLS
- Always enforce FLS in user-facing Apex controllers
🎤 One-Line Answer
"FLS controls field visibility — Apex bypasses it by default. Enforce with WITH SECURITY_ENFORCED in SOQL or stripInaccessible() to remove inaccessible fields from results gracefully."
Q19
What is "with sharing" and "without sharing" in Apex?
✅ Direct Answer
with sharing: Apex respects running user's sharing rules — SOQL returns only records the user can see. without sharing: runs in system context — ignores sharing, sees all records. Default (unspecified) is without sharing — a security vulnerability. inherited sharing: inherits calling class's context. Always be explicit.
🌍 Real World Example
LWC Account search: "with sharing" — user sees only their accounts. Nightly cleanup batch: "without sharing" — must process all expired records regardless of owner. Security finding at XYZ Company: controller missing "with sharing" returned data from other regions — emergency fix took 2 days. Lesson: always be explicit.
🔑 Key Points for Interviewer
- with sharing: respects user's record visibility
- without sharing: system context, sees all records
- inherited sharing: inherits calling class's mode
- Default (unspecified) = without sharing — always be explicit
- FLS NOT enforced by either — handle separately
🎤 One-Line Answer
"with sharing respects user record visibility. without sharing ignores sharing. Default is without sharing — ALWAYS be explicit. Use with sharing for user-facing code, without sharing only for system batch processes."
Q20
What are public groups and queues? How are they different?
✅ Direct Answer
Public Groups: collections of users, roles, or other groups — used in sharing rules, list view visibility, email distribution. Queues: special groups that OWN records — for unassigned records waiting for team members to pick up (Cases, Leads, custom objects). Queues appear as users in OwnerId field.
🌍 Real World Example
Lead Queue: all web form leads → "SDR Queue" → SDRs self-assign from queue list view. Sharing Rule: share all Accounts tagged "Enterprise" with "Enterprise Sales Team" public group. Adding new rep to group: automatically inherits all sharing rules, list view access, and email distribution. Queue: owns records. Group: shares records.
🎤 One-Line Answer
"Public Groups are user collections for sharing rules and list views. Queues own unassigned records until team members pick them up — queues appear as users in OwnerId and work with assignment rules."
Q21
What is Apex Managed Sharing?
✅ Direct Answer
Apex Managed Sharing grants record access programmatically by inserting Share objects (AccountShare, CustomObject__Share) with a custom RowCause. Unlike manual sharing, Apex Managed Sharing PERSISTS when record ownership changes — making it suitable for complex sharing scenarios that declarative rules can't handle.
🌍 Real World Example
Deal__Share share = new Deal__Share();
share.ParentId = dealId;
share.UserOrGroupId = participantId;
share.AccessLevel = 'Read';
share.RowCause = Schema.Deal__Share.RowCause.MeetingParticipant__c;
insert share;
🔑 Key Points for Interviewer
- Share objects: AccountShare, ContactShare, CustomObj__Share
- RowCause must be custom — created in object's Sharing Reason settings
- Persists through ownership changes (unlike manual sharing)
- Use when sharing logic depends on related records or dynamic conditions
- Delete shares when the condition no longer applies
🎤 One-Line Answer
"Apex Managed Sharing inserts Share objects with custom RowCause — persists through ownership changes. Use for complex sharing logic that declarative rules can't express."
Q22
What is the difference between View All and Modify All permissions?
✅ Direct Answer
View All: user can see ALL records of a specific object regardless of OWD/roles/sharing — complete bypass for read access. Modify All: user can see AND edit/delete ALL records — complete bypass for read + write. Both configured per object on profiles or permission sets. View All Data / Modify All Data are org-level admin equivalents for ALL objects.
🎤 One-Line Answer
"View All = read-only bypass of all sharing for one object. Modify All = read + write + delete bypass. Use sparingly — principle of least privilege. View All Data / Modify All Data are admin-level for all objects."
Q23
How do you troubleshoot when a user can't see a record they should have access to?
✅ Direct Answer
Debug systematically: 1) Check OWD — is record accessible at object level? 2) Check record owner's role vs user's role — is hierarchy correct? 3) Check sharing rules — does any rule grant access? 4) Check manual sharing — has anyone shared this record? 5) Check Profile CRUD — can user even see the object? Use "Why can't I see this?" Lightning diagnostic tool.
🌍 Real World Example
User: "I can't see Account ABC." Debug: OWD = Private ✓, User not in owner's role branch ✓, No sharing rule ✓, No manual sharing ✓ — root cause: user was recently moved to a different role that's no longer in the sharing path. Fix: updated role hierarchy. TCS loves this systematic debugging approach — always explain step by step.
🎤 One-Line Answer
"Debug order: OWD → Role Hierarchy → Sharing Rules → Manual Sharing → Profile CRUD. Or use Lightning's 'Why can't I see this?' tool for fastest path to root cause."
Q24
What are login hours and IP restrictions?
✅ Direct Answer
Login Hours (Profile-based): restrict which hours users can log in — e.g., 7 AM-8 PM weekdays only. IP Restrictions: restrict login to specific IP address ranges — only corporate network or VPN. Together they provide time-based and location-based access controls. Critical for regulated industries (banking, pharma) that TCS serves.
🎤 One-Line Answer
"Login Hours restrict when users can access Salesforce. IP Restrictions restrict which networks they access from. Two security layers preventing unauthorized access even with correct credentials."
Q25
What is a Permission Set Group?
✅ Direct Answer
Permission Set Group bundles multiple Permission Sets into one assignable unit — instead of assigning 5 separate PSets to every Sales Rep, create one "Sales Rep" PSG containing all 5. Assign the group; all included PSets apply automatically. Muting Permission Sets can remove specific permissions from a group without removing the PSets.
🌍 Real World Example
Before PSG: onboarding new Sales Rep = assign 6 Permission Sets one by one. After PSG: assign 1 "Sales Rep PSG" = all 6 applied instantly. New access needed company-wide? Add one PSet to the group — all 500 reps get it automatically. TCS uses this pattern for all large enterprise implementations.
🎤 One-Line Answer
"Permission Set Group bundles multiple PSets into one assignment — assign one group per job function. Muting PSets subtract specific permissions. Changes to included PSets apply to all group members automatically."
⚙️ Section 3 — Apex & Triggers
Q26–Q45 · Intermediate → Advanced · Hands-on Coding Expected at TCS
Q26
What is bulkification in Apex? Write a bulkified trigger.
✅ Direct Answer
Bulkification means writing Apex that handles multiple records efficiently — all SOQL queries and DML outside loops, processing collections. Salesforce processes up to 200 records per trigger invocation, so code must handle all 200 in one transaction without hitting governor limits.
🌍 Real World Example
// BAD - SOQL inside loop (hits governor limit)
trigger Bad on Account (after insert) {
for(Account a : Trigger.new) {
List<Contact> c = [SELECT Id FROM Contact WHERE AccountId = :a.Id];
}
}
// GOOD - Bulkified
trigger Good on Account (after insert) {
Set<Id> accIds = new Set<Id>();
for(Account a : Trigger.new) { accIds.add(a.Id); }
Map<Id, List<Contact>> contactMap = new Map<Id, List<Contact>>();
for(Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accIds]) {
if(!contactMap.containsKey(c.AccountId))
contactMap.put(c.AccountId, new List<Contact>());
contactMap.get(c.AccountId).add(c);
}
for(Account a : Trigger.new) {
List<Contact> contacts = contactMap.get(a.Id);
// process contacts safely
}
}
🔑 Key Points for Interviewer
- Never SOQL or DML inside for loops
- Use Set to collect IDs, Map for lookups, List for DML
- Trigger.new: all records in transaction (up to 200)
- Pattern: collect → query → process → DML
- TCS tests this with live coding — practice writing from memory
🎤 One-Line Answer
"Bulkification = never SOQL or DML inside loops — collect all IDs, query once with IN clause, use Map for O(1) lookups, batch DML at end. This is the #1 Apex pattern TCS tests."
Q27
What is the difference between before and after triggers?
✅ Direct Answer
Before triggers: fire before record commits — modify Trigger.new directly without DML (free), records have no Id yet on insert, used for field validation and derivation. After triggers: fire after commit — records have Ids, need explicit DML to update triggering record, used when creating/updating related records that need the new record's Id.
🌍 Real World Example
Before trigger on Lead: set Rating = 'Hot' if LeadSource = 'Web' — no DML needed, modifies Trigger.new directly. After trigger on Opportunity insert: create related Task using new Opportunity Id (only available after save). Wrong choice — using after trigger for field update wastes a DML statement unnecessarily.
🎤 One-Line Answer
"Before: modify fields without DML cost, no Id on insert. After: record has Id, use for related record creation. Don't waste a DML on after trigger when before trigger handles field updates for free."
Q28
How do you prevent trigger recursion in Apex?
✅ Direct Answer
Use a static Boolean variable in a utility class. Set to true when trigger first fires — check at trigger start and return if already true. Static variables persist for entire transaction, so trigger only runs logic once regardless of how many times it's called during the transaction.
🌍 Real World Example
// TriggerUtil class
public class TriggerUtil {
public static Boolean hasAccountTriggerRun = false;
}
// Trigger
trigger AccountTrigger on Account (after update) {
if(TriggerUtil.hasAccountTriggerRun) return;
TriggerUtil.hasAccountTriggerRun = true;
List<Account> toUpdate = new List<Account>();
for(Account a : Trigger.new) {
toUpdate.add(new Account(Id = a.Id, Description = 'Updated'));
}
if(!toUpdate.isEmpty()) update toUpdate; // Won't re-fire
}
🎤 One-Line Answer
"Static Boolean in utility class — check at trigger start, return if true, set to true on first run. Since statics persist for the transaction, logic executes only once regardless of re-entrant calls."
Q29
What is a Trigger Framework and why should you always use one?
✅ Direct Answer
Trigger Framework separates trigger logic from the trigger file — trigger file is minimal (just delegates to handler class). Handler organizes business logic by event type. Prevents multiple triggers per object, enables independent unit testing, makes code maintainable by any developer. One trigger per object — all events in one file.
🌍 Real World Example
// Trigger - minimal, delegates to handler
trigger OpportunityTrigger on Opportunity (before insert, before update, after insert, after update) {
OpportunityTriggerHandler handler = new OpportunityTriggerHandler();
if(Trigger.isBefore && Trigger.isInsert) handler.beforeInsert(Trigger.new);
if(Trigger.isBefore && Trigger.isUpdate) handler.beforeUpdate(Trigger.new, Trigger.oldMap);
if(Trigger.isAfter && Trigger.isInsert) handler.afterInsert(Trigger.new);
if(Trigger.isAfter && Trigger.isUpdate) handler.afterUpdate(Trigger.new, Trigger.oldMap);
}
// Handler - all business logic, easily testable
public with sharing class OpportunityTriggerHandler {
public void beforeInsert(List<Opportunity> newOpps) {
OpportunityService.setDefaults(newOpps);
}
public void afterInsert(List<Opportunity> newOpps) {
OpportunityService.createOnboardingTasks(newOpps);
}
}
🎤 One-Line Answer
"Trigger Framework = one trigger file delegates to handler class — separates logic from events, enables unit testing, prevents multiple trigger conflicts. TCS mandates this pattern on all projects."
Q30
What is Batch Apex and when do you use it?
✅ Direct Answer
Batch Apex processes large record sets asynchronously in chunks (up to 2,000 per execute()) with fresh governor limits per chunk. Implements Database.Batchable interface with start() (defines scope via QueryLocator), execute() (processes each chunk), finish() (post-processing). Use for processing millions of records beyond single-transaction limits.
🌍 Real World Example
global class AccountCleanupBatch implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Rating FROM Account WHERE Rating = null');
}
global void execute(Database.BatchableContext bc, List<Account> scope) {
for(Account a : scope) { a.Rating = 'Cold'; }
update scope;
}
global void finish(Database.BatchableContext bc) {
// Send completion email
}
}
// Execute: Database.executeBatch(new AccountCleanupBatch(), 200);
🔑 Key Points for Interviewer
- Max 5 concurrent batch jobs per org
- Chunk size 1-2000, default 200
- QueryLocator: handles up to 50M records
- Database.Stateful: preserves instance variables between chunks
- Database.AllowsCallouts: enables HTTP callouts in execute()
🎤 One-Line Answer
"Batch Apex processes millions of records in chunks with fresh governor limits per execute() — implement start/execute/finish, use QueryLocator for 50M record capacity. Max 5 concurrent batch jobs."
Q31
What is Queueable Apex and how is it different from @future?
✅ Direct Answer
@future: simple async, primitive parameters only, no chaining, no monitoring, no SObjects. Queueable: implements Queueable interface, accepts complex types including SObjects, chainable (enqueue in execute()), has Job ID for monitoring, supports callouts with Database.AllowsCallouts. Queueable is the modern replacement for @future.
🎤 One-Line Answer
"Queueable > @future: accepts SObjects, chainable, Job ID for monitoring, supports callouts. Use Queueable for all modern async needs; @future only for simple fire-and-forget with primitive parameters."
Q32
What is Test.startTest() and Test.stopTest() and why are they essential?
✅ Direct Answer
Test.startTest(): resets governor limits for code under test — test setup doesn't eat into the unit being tested's limits. Test.stopTest(): forces all async operations (@future, Batch, Queueable) to execute synchronously. Without stopTest(), async jobs haven't run yet when you write assertions — tests would fail or miss async results.
🌍 Real World Example
@isTest
static void testBatch() {
List<Account> accs = TestDataFactory.createAccounts(200);
insert accs;
Test.startTest(); // Reset limits
Database.executeBatch(new AccountCleanupBatch(), 200);
Test.stopTest(); // Batch runs synchronously RIGHT NOW
// NOW assert on batch results
Integer updated = [SELECT COUNT() FROM Account WHERE Rating = 'Cold'];
System.assertEquals(200, updated, 'All accounts should have Cold rating');
}
🎤 One-Line Answer
"startTest() resets governor limits. stopTest() forces async work to complete synchronously — without stopTest(), assertions run before async finishes. Always wrap tested code between them."
Q33
What is a wrapper class in Apex and when do you use it?
✅ Direct Answer
Wrapper class bundles multiple data types (SObjects, primitives, computed values) into one unit for passing between Apex and LWC/Visualforce. Use when a single SObject can't represent the data structure needed by the UI — for example combining Account data with isSelected flag and computed opportunity count.
🌍 Real World Example
public class AccountWrapper {
@AuraEnabled public Account account { get; set; }
@AuraEnabled public Boolean isSelected { get; set; }
@AuraEnabled public Integer opportunityCount { get; set; }
public AccountWrapper(Account acc, Integer oppCount) {
this.account = acc;
this.isSelected = false;
this.opportunityCount = oppCount;
}
}
🎤 One-Line Answer
"Wrapper class bundles SObjects + computed fields into one unit for LWC — use when a single SObject can't represent the full data structure the UI needs. @AuraEnabled on each property."
Q34
How do you mock HTTP callouts in Apex tests?
✅ Direct Answer
Test.setMock() registers a class implementing HttpCalloutMock that intercepts HTTP requests during test execution — returning a predefined response instead of making a real API call (blocked in test context). Without setMock(), any test triggering a callout throws "Callout not allowed" exception.
🌍 Real World Example
@isTest
public class MockResponse implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HTTPResponse res = new HTTPResponse();
res.setBody('{"status":"success","id":"12345"}');
res.setStatusCode(200);
return res;
}
}
@isTest
static void testCallout() {
Test.setMock(HttpCalloutMock.class, new MockResponse());
Test.startTest();
String result = ERPService.createOrder('ORD-001');
Test.stopTest();
System.assertEquals('12345', result);
}
🎤 One-Line Answer
"Test.setMock() registers HttpCalloutMock implementation — intercepts HTTP requests and returns predefined response. Without it, callout tests fail with 'Callout not allowed' exception."
Q35
What is the difference between Database.insert() and the insert DML statement?
✅ Direct Answer
insert statement: all-or-nothing — if any record fails, entire operation rolls back. Database.insert(records, false): partial success — inserts successful records, returns Database.SaveResult[] with per-record success/failure. Use Database.insert for bulk integrations where partial success is acceptable.
🌍 Real World Example
Database.SaveResult[] results = Database.insert(accounts, false);
for(Database.SaveResult sr : results) {
if(sr.isSuccess()) {
System.debug('Inserted: ' + sr.getId());
} else {
for(Database.Error err : sr.getErrors()) {
System.debug('Error: ' + err.getMessage());
}
}
}
🎤 One-Line Answer
"insert keyword = all-or-nothing. Database.insert(list, false) = partial success — successful records save, failed ones return per-record errors without rolling back the rest."
Q36
What is @InvocableMethod and how does it connect Apex to Flows?
✅ Direct Answer
@InvocableMethod exposes an Apex method as a Flow Action — callable from Record-Triggered Flows, Screen Flows, and Auto-launched Flows via the Action element. Bridges declarative Flow with programmatic Apex for logic too complex for Flow alone (external callouts, complex calculations).
🌍 Real World Example
public class TaxCalculator {
@InvocableMethod(label='Calculate GST' category='Order')
public static List<Result> calculateTax(List<Request> requests) {
List<Result> results = new List<Result>();
for(Request req : requests) {
Result res = new Result();
res.taxAmount = req.orderAmount * 0.18;
results.add(res);
}
return results;
}
public class Request { @InvocableVariable public Decimal orderAmount; }
public class Result { @InvocableVariable public Decimal taxAmount; }
}
🎤 One-Line Answer
"@InvocableMethod exposes Apex as Flow Action — bridges Flow's declarative power with Apex's programmatic capability for callouts, complex calculations, and operations Flow can't natively perform."
Q37
What are Apex best practices for writing test classes?
✅ Direct Answer
Key practices: 75% minimum coverage (target 85%+), use @TestSetup for shared data, never seeAllData=true, use TestDataFactory for consistency, test positive AND negative scenarios, meaningful assertions with failure messages, mock all callouts with Test.setMock(), wrap async code with startTest/stopTest.
🔑 Key Points for Interviewer
- @TestSetup: runs once before all tests — share data setup cost
- Never seeAllData=true: isolates tests from org data changes
- TestDataFactory: centralized test data for consistency
- Test positive AND negative/exception scenarios
- Coverage proves execution; assertions prove correctness
🎤 One-Line Answer
"@TestSetup for shared data, seeAllData=false, TestDataFactory, test positive AND negative, meaningful assertions, mock callouts — coverage proves execution, assertions prove correctness."
Q38
What is a Custom Exception in Apex?
✅ Direct Answer
Custom Exceptions extend the Exception class in one line and allow throwing domain-specific errors with meaningful names. Enable specific catch blocks per error type and convey business context that generic DmlException or QueryException can't express.
🌍 Real World Example
public class OrderValidationException extends Exception {}
public class InsufficientInventoryException extends Exception {}
// In service class
if(order.Amount__c <= 0) {
throw new OrderValidationException('Order amount must be greater than zero');
}
// Caller catches specifically
try { OrderService.createOrder(order); }
catch(InsufficientInventoryException e) { /* show inventory alert */ }
catch(OrderValidationException e) { /* show validation error */ }
🎤 One-Line Answer
"Custom Exception extends Exception in one line — enables specific catch blocks per error type, conveys business context. 'public class MyException extends Exception {}' is all you need."
Q39
What is a Schedulable Apex class?
✅ Direct Answer
Schedulable Apex implements the Schedulable interface with one execute() method — runs on a CRON-based schedule. Best practice: never do heavy work directly in execute() — delegate to Batch Apex or Queueable instead. Schedule via System.schedule() in Apex or through Setup → Scheduled Jobs UI.
🌍 Real World Example
public class NightlyCleanup implements Schedulable {
public void execute(SchedulableContext ctx) {
Database.executeBatch(new ExpiredRecordsBatch(), 200);
}
}
// Schedule: every day at 2 AM
String cron = '0 0 2 * * ?';
System.schedule('Nightly Cleanup', cron, new NightlyCleanup());
🎤 One-Line Answer
"Schedulable implements execute() and runs on CRON schedule. Always delegate heavy work to Batch Apex inside execute() — don't process records directly in the schedulable method."
Q40
What is Change Data Capture (CDC)?
✅ Direct Answer
CDC automatically publishes change events whenever Salesforce records are created, updated, deleted, or undeleted — external systems subscribe via CometD or Apex triggers on __ChangeEvent objects. Eliminates API polling — instead of checking every 5 minutes what changed, receive instant notification. Replay window: 3 days.
🌍 Real World Example
Old approach: ERP polls Salesforce REST API every 5 minutes — 288 API calls/day per object. CDC: ERP subscribes to AccountChangeEvent — receives changes within seconds. changedFields header tells exactly which fields changed — no need to compare full records. Zero polling, real-time, 99% fewer API calls.
🎤 One-Line Answer
"CDC auto-publishes record change events — external systems subscribe for real-time sync without API polling. 3-day replay window. changedFields header shows exactly which fields changed."
Q41
What is the difference between a static method and an instance method?
✅ Direct Answer
Static methods belong to the class — called as ClassName.method(), no instantiation, no access to instance variables, shared state. Instance methods belong to an object — called on new ClassName(), have access to all instance variables, per-object state. Static variables persist for entire transaction (used for recursion prevention).
🎤 One-Line Answer
"Static = belongs to class, no instance needed, shared state. Instance = belongs to object, requires new ClassName(), has own state. Static variables persist for entire transaction — used for recursion prevention flags."
Q42
Write an Apex trigger to prevent duplicate Accounts based on Account Name.
🌍 Real World Example
trigger PreventDuplicateAccount on Account (before insert, before update) {
// Collect all names being inserted/updated
Set<String> names = new Set<String>();
for(Account a : Trigger.new) {
if(a.Name != null) names.add(a.Name.toLowerCase());
}
// Query existing accounts with same names
Map<String, Account> existingMap = new Map<String, Account>();
for(Account a : [SELECT Id, Name FROM Account WHERE Name IN :names]) {
existingMap.put(a.Name.toLowerCase(), a);
}
// Check each incoming account
for(Account a : Trigger.new) {
String nameLower = a.Name != null ? a.Name.toLowerCase() : '';
if(existingMap.containsKey(nameLower)) {
// For updates, exclude the record itself
Account existing = existingMap.get(nameLower);
if(Trigger.isInsert || existing.Id != a.Id) {
a.Name.addError('An Account with this name already exists: ' + a.Name);
}
}
}
}
🎤 One-Line Answer
"Before trigger: collect names, query existing with IN clause (bulkified), check each incoming — addError() if duplicate found. Handle update case by excluding the record itself from duplicate check."
Q43
What is the @AuraEnabled annotation?
✅ Direct Answer
@AuraEnabled exposes an Apex method to Lightning components (LWC and Aura). Required for any Apex method called from LWC via @wire or imperative calls. cacheable=true enables client-side caching for read-only methods (required for @wire). Methods must be public or global static.
🌍 Real World Example
public class AccountController {
// cacheable=true: required for @wire, cached client-side
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts(String industry) {
return [SELECT Id, Name, Industry FROM Account
WHERE Industry = :industry WITH SECURITY_ENFORCED
LIMIT 100];
}
// No cacheable: for DML operations (insert/update/delete)
@AuraEnabled
public static void updateAccount(Id accountId, String name) {
Account a = new Account(Id = accountId, Name = name);
update a;
}
}
🎤 One-Line Answer
"@AuraEnabled exposes Apex to LWC. cacheable=true enables client caching and is required for @wire. Omit cacheable for DML operations — cached methods cannot perform data modifications."
Q44
What is Apex REST web service (@RestResource)?
✅ Direct Answer
@RestResource exposes Apex class as custom REST endpoint at /services/apexrest/. Annotate with @HttpGet, @HttpPost, @HttpPut, @HttpDelete for HTTP method handling. Access request/response via RestContext. Requires Connected App + OAuth authentication from external callers.
🌍 Real World Example
@RestResource(urlMapping='/orders/*')
global class OrderService {
@HttpGet
global static Order__c getOrder() {
String orderId = RestContext.request.requestURI.substringAfterLast('/');
return [SELECT Id, Name, Amount__c FROM Order__c WHERE Id = :orderId];
}
@HttpPost
global static String createOrder(String productName, Decimal amount) {
Order__c o = new Order__c(Name = productName, Amount__c = amount);
insert o;
return o.Id;
}
}
🎤 One-Line Answer
"@RestResource creates custom REST endpoint at /services/apexrest/ — use @HttpGet/@HttpPost annotations, access via RestContext. Requires OAuth from external callers."
Q45
What are the OOPS concepts in Apex with examples?
✅ Direct Answer
Encapsulation (private variables, public methods), Inheritance (virtual/extends/override), Polymorphism (method overloading/overriding), Abstraction (abstract classes and interfaces). Database.Batchable and Queueable are interfaces — real Salesforce examples of abstraction.
🌍 Real World Example
// Inheritance + Polymorphism
public virtual class BaseTriggerHandler {
public virtual void beforeInsert(List<SObject> records) {}
public virtual void afterInsert(List<SObject> records) {}
}
public class AccountHandler extends BaseTriggerHandler {
public override void beforeInsert(List<SObject> records) {
// Account-specific logic
}
}
// Abstraction — Interface
public interface IProcessor { void process(List<SObject> records); }
// Database.Batchable IS an interface — Apex framework example
🎤 One-Line Answer
"Apex supports all 4 OOP pillars — Encapsulation (private/public), Inheritance (virtual/extends), Polymorphism (override), Abstraction (abstract/interface). Database.Batchable itself is an interface — a built-in Salesforce abstraction example."
🔍 Section 4 — SOQL & SOSL
Q46–Q55 · Intermediate · Query Skills Tested at TCS
Q46
What is the difference between SOQL and SOSL?
✅ Direct Answer
SOQL: queries one object at a time (with related objects), returns List<SObject>, precise WHERE filtering, 100 queries per transaction. SOSL: searches across multiple objects using text index, returns List<List<SObject>>, faster for cross-object text search, 20 per transaction.
🌍 Real World Example
// SOQL - precise, one object
List<Account> accs = [SELECT Id, Name FROM Account WHERE Industry = 'Technology'];
// SOSL - cross-object text search
List<List<SObject>> results = [FIND 'Accenture*' IN ALL FIELDS
RETURNING Account(Id, Name), Contact(Id, Name, Email)];
List<Account> accounts = (List<Account>) results[0];
🎤 One-Line Answer
"SOQL queries one object precisely (WHERE clause). SOSL searches text across multiple objects simultaneously. Use SOQL for data retrieval; SOSL for global search scenarios."
Q47
Write a parent-to-child and child-to-parent SOQL query.
🌍 Real World Example
// Child-to-Parent: dot notation
List<Contact> contacts = [
SELECT Id, Name, Account.Name, Account.Industry, Account.Owner.Name
FROM Contact WHERE Account.Industry = 'Technology'
];
// Parent-to-Child: subquery
List<Account> accounts = [
SELECT Id, Name,
(SELECT Id, Name, Email FROM Contacts WHERE IsActive__c = true),
(SELECT Id, Amount, StageName FROM Opportunities WHERE IsClosed = false)
FROM Account WHERE Type = 'Customer'
];
// Custom relationship: replace __c with __r
// Order__c → Order__r (child-to-parent)
// Order_Line_Items__r (parent-to-child, pluralized)
🎤 One-Line Answer
"Child-to-parent: Account.Name dot notation. Parent-to-child: (SELECT Id FROM Contacts) subquery. Custom: replace __c with __r for relationship traversal."
Q48
What is SOQL injection and how do you prevent it?
✅ Direct Answer
SOQL injection occurs when user input is directly concatenated into a dynamic SOQL string — allowing attackers to modify query logic. Prevent with: bind variables (:variable — completely injection-proof), or String.escapeSingleQuotes() for dynamic field/object names.
🌍 Real World Example
// VULNERABLE
String name = ApexPages.currentPage().getParameters().get('name');
// Attacker: ' OR Name != '' → exposes all accounts!
String q = 'SELECT Id FROM Account WHERE Name = \'' + name + '\'';
// SAFE - bind variable (best approach)
String q = 'SELECT Id FROM Account WHERE Name = :name';
List<Account> accs = Database.query(q);
// SAFE - escaped (for dynamic field/object names)
String safeName = String.escapeSingleQuotes(name);
String q2 = 'SELECT Id FROM Account WHERE Name = \'' + safeName + '\'';
🎤 One-Line Answer
"SOQL injection manipulates dynamic query logic — prevent with bind variables (:variable) which are completely injection-proof. Only use String.escapeSingleQuotes() when bind variables can't be used."
Q49
What are aggregate functions in SOQL?
🌍 Real World Example
AggregateResult[] results = [
SELECT StageName,
COUNT(Id) oppCount,
SUM(Amount) totalValue,
AVG(Amount) avgDeal,
MAX(Amount) biggestDeal
FROM Opportunity
WHERE CloseDate = THIS_FISCAL_YEAR
GROUP BY StageName
HAVING SUM(Amount) > 500000
ORDER BY SUM(Amount) DESC
];
for(AggregateResult ar : results) {
System.debug('Stage: ' + ar.get('StageName') +
' Count: ' + ar.get('oppCount') +
' Total: ' + ar.get('totalValue'));
}
🔑 Key Points for Interviewer
- Functions: COUNT, SUM, AVG, MIN, MAX, COUNT_DISTINCT
- Returns AggregateResult[] — access with ar.get('fieldOrAlias')
- WHERE: filters before aggregation. HAVING: filters after GROUP BY
- GROUP BY ROLLUP: adds subtotals
🎤 One-Line Answer
"SOQL aggregates: COUNT/SUM/AVG/MIN/MAX with GROUP BY return AggregateResult[]. WHERE filters before aggregation; HAVING filters after. Access values with ar.get('alias')."
Q50
What are SOQL Date Literals? Give 5 examples.
🌍 Real World Example
// 5 practical examples
// 1. Leads created in last 30 days
[SELECT Id FROM Lead WHERE CreatedDate = LAST_N_DAYS:30]
// 2. Open opportunities closing this quarter
[SELECT Id FROM Opportunity WHERE CloseDate = THIS_FISCAL_QUARTER AND IsClosed = false]
// 3. Cases not updated in 7 days
[SELECT Id FROM Case WHERE LastModifiedDate < LAST_N_DAYS:7 AND Status != 'Closed']
// 4. Accounts created this month
[SELECT Id FROM Account WHERE CreatedDate = THIS_MONTH]
// 5. Tasks due in next 5 days
[SELECT Id FROM Task WHERE ActivityDate = NEXT_N_DAYS:5]
🎤 One-Line Answer
"Date Literals (TODAY, LAST_N_DAYS:30, THIS_FISCAL_QUARTER) dynamically calculate dates — no hardcoded values, perfect for scheduled batch queries that must always run relative to execution time."
Q51
What is a selective query and why does it matter?
✅ Direct Answer
A selective query filters on indexed fields — using index scan instead of full table scan. Non-selective queries on objects with >100K records can cause QUERY_TIMEOUT errors. A query is selective when it returns less than 10% of total records or less than 333K, whichever is less.
🌍 Real World Example
500K Account records. WHERE Custom_Field__c = 'Value' (non-indexed) — full table scan, 10-second timeout. Fix: request custom index on that field via Salesforce Support, or add auto-indexed field to WHERE (CreatedDate, OwnerId, Id). Use Query Plan tool in Developer Console to check "TableScan" vs "Index".
🎤 One-Line Answer
"Selective queries filter on indexed fields — non-selective on large objects cause timeouts. Auto-indexed: Id, Name, OwnerId, CreatedDate. Use Query Plan tool to verify; request custom indexes for frequently-queried fields."
Q52
What is the difference between Database.query() and static SOQL?
✅ Direct Answer
Static SOQL: compile-time validation, always safe from injection, used for known queries. Database.query(): dynamic at runtime — object/field names not known at compile time, susceptible to SOQL injection if not sanitized, used for generic utilities and configurable reporting tools.
🌍 Real World Example
// Static SOQL - compile-time validated, always safe
List<Account> accs = [SELECT Id, Name FROM Account WHERE Industry = :industry];
// Dynamic SOQL - runtime, sanitize carefully
String objectName = String.escapeSingleQuotes(userInput);
String q = 'SELECT Id, Name FROM ' + objectName + ' LIMIT 100';
List<SObject> records = Database.query(q);
// Database.countQuery for dynamic COUNT
Integer count = Database.countQuery('SELECT COUNT() FROM ' + objectName);
🎤 One-Line Answer
"Static SOQL: compile-time validated, always injection-safe. Database.query(): runtime dynamic, use when object/field unknown at compile time — always sanitize with bind variables or escapeSingleQuotes()."
Q53
What is FOR UPDATE in SOQL?
✅ Direct Answer
FOR UPDATE locks queried records at the database level — no other transaction can modify them until current transaction completes. Prevents race conditions when multiple concurrent processes read-then-write the same records (inventory deduction, counter decrement). UNABLE_TO_LOCK_ROW error if lock can't be acquired within 10 seconds.
🎤 One-Line Answer
"FOR UPDATE locks records for transaction duration — prevents race conditions when concurrent processes read-then-write same records. Use carefully — misuse causes UNABLE_TO_LOCK_ROW errors."
Q54
What is the SOQL query limit for sync vs async Apex?
✅ Direct Answer
Synchronous (triggers, controllers): 100 SOQL queries per transaction. Asynchronous (@future, Batch execute(), Queueable): 200 SOQL queries per transaction. Both share the same 150 DML statements and 10,000 DML rows. Batch execute() gets fresh limits per chunk.
🎤 One-Line Answer
"Sync: 100 SOQL. Async (@future, Batch, Queueable): 200 SOQL. Batch execute() gets fresh limits per chunk — move complex multi-query logic to async for doubled SOQL headroom."
Q55
What is Database.getQueryLocator() vs Database.query() in Batch Apex?
✅ Direct Answer
Database.getQueryLocator(): server-side cursor, handles 50 million records efficiently in Batch start(). Database.query(): loads results into heap memory, limited to ~50K records by heap size. Always use getQueryLocator in Batch start() — never Database.query() for large result sets.
🎤 One-Line Answer
"getQueryLocator() handles 50M records via server-side cursor in Batch start(). Database.query() loads into heap — limited to ~50K. Always use getQueryLocator in Batch Apex."
💻 Section 5 — Lightning Web Components (LWC)
Q56–Q65 · Intermediate · Increasingly Asked at TCS
Q56
What is LWC and how is it different from Aura?
✅ Direct Answer
LWC uses modern web standards — native JavaScript ES6+, Shadow DOM, Web Components. Aura uses Salesforce's proprietary framework with custom syntax. LWC is significantly faster (native browser APIs), better developer experience (standard JS tools work), and Salesforce's strategic direction. Aura is legacy — maintained but no new features.
🎤 One-Line Answer
"LWC uses native web standards (ES6+, Shadow DOM) — faster and more developer-friendly than Aura's proprietary framework. Salesforce's strategic direction; use LWC for all new components."
Q57
Explain the LWC lifecycle hooks.
✅ Direct Answer
Lifecycle order: constructor() (once, first — no DOM access) → connectedCallback() (once, when added to DOM — safe for data loading) → render() (every render) → renderedCallback() (after EVERY render — fires multiple times!) → disconnectedCallback() (once, on removal — cleanup here). errorCallback() catches child component errors.
🌍 Real World Example
export default class MyComponent extends LightningElement {
isInitialized = false;
connectedCallback() {
this.loadData(); // Safe — runs once
}
renderedCallback() {
if(this.isInitialized) return; // CRITICAL guard!
this.isInitialized = true;
// DOM access safe after first render
const el = this.template.querySelector('canvas');
if(el) this.initChart(el);
}
}
🎤 One-Line Answer
"constructor (1x, no DOM) → connectedCallback (1x, data loading) → renderedCallback (EVERY render, guard with isInitialized boolean!) → disconnectedCallback (1x, cleanup). TCS's most asked LWC question."
Q58
What is the difference between @api, @track, and @wire?
🌍 Real World Example
import { LightningElement, api, track, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
export default class AccountDashboard extends LightningElement {
@api recordId; // PUBLIC — parent passes this in HTML
@track filters = {}; // REACTIVE — deep mutations tracked
@wire(getAccounts, { accId: '$recordId' }) // $ = reactive param
wiredAccounts({ data, error }) {
if(data) this.accounts = data;
if(error) this.error = error.body.message;
}
}
🔑 Key Points for Interviewer
- @api: public, parent-to-child data flow
- @track: reactive deep object/array mutations
- @wire: declarative Apex binding, $ prefix = reactive parameter
- @wire returns {data, error} — always check both
- Wire re-fires automatically when reactive ($) params change
🎤 One-Line Answer
"@api = public parent access. @track = reactive deep mutations. @wire = declarative Apex binding that auto-refires when $ parameters change — returns {data, error}."
Q59
How do parent and child LWC components communicate?
✅ Direct Answer
Parent → Child: @api properties. Child → Parent: CustomEvent via dispatchEvent(). Sibling/Unrelated: Lightning Message Service (LMS). Each pattern is unidirectional by design for predictable data flow.
🌍 Real World Example
// Child dispatches event to parent
handleClick() {
this.dispatchEvent(new CustomEvent('selected', {
detail: { productId: this.product.Id },
bubbles: true,
composed: true // Cross Shadow DOM boundary
}));
}
// Parent HTML listens
// <c-child onselected={handleSelected}></c-child>
// Parent JS handles
handleSelected(event) {
const productId = event.detail.productId;
this.selectedId = productId;
}
🎤 One-Line Answer
"Parent→Child: @api properties. Child→Parent: CustomEvent with detail payload. Siblings: Lightning Message Service. bubbles + composed needed for event to cross Shadow DOM boundaries."
Q60
What is Lightning Message Service (LMS)?
✅ Direct Answer
LMS enables communication between LWC, Aura, and Visualforce components that have no parent-child relationship — across different DOM trees on the same Lightning page. Uses a Message Channel (metadata file). Publisher calls publish(); subscribers call subscribe(). Always unsubscribe in disconnectedCallback to prevent memory leaks.
🎤 One-Line Answer
"LMS enables cross-component messaging between unrelated LWC, Aura, and VF on same page via Message Channels. Always unsubscribe in disconnectedCallback — memory leak if you forget."
Q61
How do you call Apex imperatively vs @wire in LWC?
🌍 Real World Example
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
import saveAccount from '@salesforce/apex/AccountController.saveAccount';
import { refreshApex } from '@salesforce/apex';
// @wire: auto-calls, reactive
@wire(getAccounts, { type: 'Customer' })
wiredResult;
// Imperative: user-triggered, full control
async handleSave() {
try {
await saveAccount({ data: this.formData });
await refreshApex(this.wiredResult); // Refresh wire after save
} catch(error) {
this.error = error.body.message;
}
}
🎤 One-Line Answer
"@wire: auto-calls, reactive to param changes, cacheable=true. Imperative: Promise-based, user-triggered, required for DML. refreshApex() syncs wire after imperative changes."
Q62
What is Shadow DOM in LWC and how does it affect CSS?
✅ Direct Answer
Shadow DOM creates CSS encapsulation per component — parent styles don't cascade into children, child styles don't leak out. To pass styles across boundaries, use CSS custom properties (variables). :host selector styles the component's root element from within.
🌍 Real World Example
/* Parent CSS — DOES NOT reach child component */
.card { background: red; } /* blocked by Shadow DOM */
/* Pass styling via CSS custom properties */
:host { --card-bg: blue; --card-padding: 16px; }
/* Child reads parent's variable */
.card { background: var(--card-bg, white); padding: var(--card-padding, 8px); }
🎤 One-Line Answer
"Shadow DOM encapsulates CSS per component — no style leaking in or out. Use CSS custom properties (--variables) to pass styling across Shadow DOM boundaries into child components."
Q63
What is NavigationMixin in LWC?
🌍 Real World Example
import { NavigationMixin } from 'lightning/navigation';
export default class NavDemo extends NavigationMixin(LightningElement) {
viewRecord(recordId) {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: { recordId: recordId, actionName: 'view' }
});
}
openExternal() {
this[NavigationMixin.Navigate]({
type: 'standard__webPage',
attributes: { url: 'https://www.sfinterviewpro.com' }
});
}
}
🎤 One-Line Answer
"NavigationMixin(LightningElement) enables programmatic navigation — this[NavigationMixin.Navigate]({type, attributes}) for records, object pages, or external URLs. GenerateUrl returns URL without navigating."
Q64
What is lightning-record-edit-form and when do you use it?
✅ Direct Answer
lightning-record-edit-form handles FLS, validation rules, and field type rendering automatically — zero Apex needed. Use when building standard create/edit forms that respect Salesforce security. Use custom Apex only for multi-object saves, complex pre-save logic, or non-standard behavior.
🎤 One-Line Answer
"lightning-record-edit-form = zero Apex, auto FLS, auto validation rules, correct field rendering. Use custom Apex only for multi-object saves or complex pre-save business logic."
Q65
What are getters in LWC and why are they preferred over inline template expressions?
✅ Direct Answer
Getters compute values in JavaScript instead of templates — LWC templates only support simple property references, no complex expressions. Getters auto-recompute when underlying reactive properties change and are independently unit-testable.
🌍 Real World Example
// Use getters instead of complex template expressions
get hasData() { return this.accounts?.length > 0; }
get totalValue() {
if(!this.accounts) return '£0';
return '£' + this.accounts.reduce((sum, a) => sum + (a.Amount || 0), 0).toLocaleString();
}
get isLoading() { return !this.accounts && !this.error; }
// Template: {hasData}, {totalValue}, {isLoading}
// Clean, testable, reactive automatically
🎤 One-Line Answer
"Getters compute values in JS instead of templates — auto-recompute when reactive properties change, independently testable. LWC templates don't support complex expressions — always use getters."
🔄 Section 6 — Flows & Automation
Q66–Q75 · Intermediate · TCS Tests Modern Automation Knowledge
Q66
What are the different types of Flows in Salesforce?
✅ Direct Answer
Record-Triggered Flow: auto-fires on record create/update/delete — Before Save (fast, no DML cost) or After Save. Screen Flow: user-facing guided process. Scheduled Flow: time-based automation. Auto-launched Flow: programmatically called. Platform Event-Triggered: reacts to platform events.
🌍 Real World Example
Record-Triggered Before Save: Opportunity saved → auto-set Description = "Owned by " + Owner.Name (no DML). After Save: Stage = Closed Won → create 5 Tasks + send email. Screen Flow: 4-step wizard for guided quote creation embedded in LWC. Scheduled: every Monday, update stale Leads status.
🎤 One-Line Answer
"Five Flow types: Record-Triggered (Before/After Save), Screen (UI wizard), Scheduled (time-based), Auto-launched (programmatic), Platform Event. Choose based on what initiates the automation."
Q67
What is the difference between Before Save and After Save Record-Triggered Flows?
✅ Direct Answer
Before Save: runs before record commits to database — can modify triggering record's fields without DML (free, fast), cannot create/update related records. After Save: runs after commit — can create/update related records, but modifying the triggering record itself requires explicit DML (costs governor limits). Before Save runs BEFORE before triggers.
🎤 One-Line Answer
"Before Save: modify triggering record for free (no DML), fast. After Save: create related records but costs DML. Before Save runs BEFORE before triggers — important order of execution change."
Q68
What is $Record vs $Record__Prior in Record-Triggered Flows?
✅ Direct Answer
$Record: current field values after the user's changes. $Record__Prior: field values before the change — only available in update flows, null for create. Compare both to detect specific field changes and prevent unnecessary Flow execution on every save.
🌍 Real World Example
Stage Change Flow: Entry condition = StageName != $Record__Prior.StageName. Flow only fires when Stage actually changes — not every Opportunity save. Without this: Flow fires and creates duplicate onboarding tasks whenever any field is updated on the Opportunity.
🎤 One-Line Answer
"$Record = current values. $Record__Prior = pre-change values (update only). Compare in entry conditions to fire Flow only when specific fields change — not on every record save."
Q69
How do you prevent recursion in a Record-Triggered Flow?
✅ Direct Answer
Use Entry Conditions with $Record vs $Record__Prior comparison — Flow only fires when specific fields actually change. Also set "Only when record is updated to meet condition requirements" option. This prevents the Flow from re-firing when its own DML updates another field on the same record.
🎤 One-Line Answer
"Prevent Flow recursion with $Record__Prior comparison in entry conditions — CHANGED operator ensures Flow only fires on specific field change, not when Flow's own updates re-trigger it."
Q70
When do you choose Flow over Apex?
✅ Direct Answer
Choose Flow when: simple-moderate logic, standard CRUD, admin/business-user maintainability needed, no external callouts. Choose Apex when: complex business logic, external HTTP callouts, batch processing millions, custom REST endpoints, performance-critical operations. TCS principle: Flow first, Apex only when Flow genuinely can't handle it.
🎤 One-Line Answer
"Flow for simple/moderate logic admins can maintain. Apex for complex logic, external callouts, and batch volumes. TCS principle: Flow first — reach for Apex only when Flow genuinely cannot handle the requirement."
Q71
What is an Approval Process and how does it differ from a Flow?
✅ Direct Answer
Approval Process: structured human decision-making — record submitted, locked from editing, routed to approvers who approve/reject, actions fire on approval or rejection. Flow: automated without human approval gate. Combine them: Approval Process triggers Flows on approval/rejection for post-decision automation.
🎤 One-Line Answer
"Approval Process = explicit human sign-off with record locking. Flow = automated. Combine: Approval Process triggers Flows on approval and rejection for post-decision automation."
Q72
What are the key elements available in Flow Builder?
✅ Direct Answer
Core elements: Screen (user UI), Get/Create/Update/Delete Records (DML operations), Action (Invocable Method, email, Chatter), Decision (if/else branching), Loop (iterate collection), Assignment (set variables), Subflow (call another Flow), Wait (time-based pause), Transform (data mapping).
🎤 One-Line Answer
"Key Flow elements: Screen (UI), Get/Create/Update/Delete Records (DML), Decision (branching), Loop (iteration), Assignment (variables), Action (Apex/email), Subflow (reuse), Wait (time) — each with a specific purpose."
Q73
What is a subflow and when do you use it?
✅ Direct Answer
Subflow calls another Auto-launched Flow from within a parent Flow — passing input/output variables. Use to reuse common logic across multiple parent Flows (DRY principle). Update shared logic in one subflow — all parent Flows benefit automatically without individual updates.
🎤 One-Line Answer
"Subflow calls reusable Auto-launched Flow with input/output variables — DRY principle. Shared notification logic in one subflow called by 5 parent Flows. Update once, propagates everywhere."
Q74
How do you handle errors (faults) in Flows?
✅ Direct Answer
Connect Fault Connectors from DML/action elements to error-handling paths. Store {!$Flow.FaultMessage} in a variable, create a Flow_Error_Log__c record for audit trail, send admin email notification. Without fault connectors, Flow errors show raw technical messages to users.
🎤 One-Line Answer
"Connect Fault Connectors to error paths — log {!$Flow.FaultMessage} to error object, notify admins, show user-friendly messages. Unconnected faults expose raw errors to users."
Q75
What is a Scheduled Flow and what are its limitations?
✅ Direct Answer
Scheduled Flow runs on a defined schedule — no code, easy setup. Limitations vs Scheduled Apex: not guaranteed exact timing (can be delayed), not for high volumes (use Batch Apex), minimum 1-hour frequency, can pause during Salesforce maintenance. Use Scheduled Apex Batch for mission-critical timing and millions of records.
🎤 One-Line Answer
"Scheduled Flow: no-code time-based automation — pauses under limits, not designed for millions of records. Use Scheduled Apex Batch for mission-critical timing, high volumes, or sub-hourly frequency."
🔗 Section 7 — Integration & Deployment
Q76–Q85 · Intermediate → Advanced · TCS Is Integration-Heavy
Q76
What is the difference between REST API and SOAP API in Salesforce?
✅ Direct Answer
REST API: lightweight, JSON/XML, HTTP methods (GET/POST/PUT/PATCH/DELETE), modern standard. SOAP API: XML-based, WSDL contract, enterprise-legacy. Salesforce recommends REST for all new integrations — higher limits, easier client libraries. TCS uses REST for all new integrations; SOAP only for legacy systems.
🎤 One-Line Answer
"REST: JSON, HTTP verbs, modern, recommended. SOAP: XML, WSDL, enterprise legacy. TCS uses REST for all new integrations — simpler, faster to build, better tooling support."
Q77
What are Named Credentials and why must you use them?
✅ Direct Answer
Named Credentials store external endpoint URLs and authentication details securely — encrypted, not visible in code. Callouts reference them as 'callout:CredentialName'. Auto-handle OAuth token refresh, require no Remote Site Settings, and keep credentials out of source code and version control.
🌍 Real World Example
// WITHOUT Named Credentials - SECURITY RISK
req.setEndpoint('https://api.erp.com/orders');
req.setHeader('Authorization', 'Bearer hardcoded_token'); // In GitHub = breach!
// WITH Named Credentials - SECURE
req.setEndpoint('callout:ERP_Integration/orders');
// No credentials in code. Token refresh handled automatically.
🎤 One-Line Answer
"Named Credentials store endpoints + auth securely — never hardcode credentials in Apex. Referenced as 'callout:Name', auto-refreshes OAuth tokens, no Remote Site Settings needed."
Q78
Why can't you make HTTP callouts directly from Apex triggers?
✅ Direct Answer
Triggers execute in DML context — Salesforce throws "Callout not allowed after uncommitted work" if you try to make an HTTP callout while a DML transaction is open. Solution: use @future(callout=true) or Queueable with Database.AllowsCallouts — these async methods run in a separate transaction after the DML commits.
🎤 One-Line Answer
"Triggers can't make callouts — open DML transaction blocks them. Use @future(callout=true) or Queueable with AllowsCallouts to move callouts to async context after DML commits."
Q79
What is the Bulk API and when do you use it?
✅ Direct Answer
Bulk API 2.0 processes large data volumes (millions of records) asynchronously via CSV job — create job, upload CSV, poll for results. REST API handles small real-time operations (up to 200 records per sObject Collections). Data Loader uses Bulk API 2.0 under the hood. Daily limit: 150 million records.
🎤 One-Line Answer
"Bulk API 2.0 processes millions of records asynchronously via CSV jobs — use for 10,000+ records. REST API for real-time small operations. Data Loader uses Bulk API under the hood."
Q80
What is Outbound Message in Salesforce?
✅ Direct Answer
Outbound Messages send SOAP XML notifications to external endpoints when triggered by Workflow/Approval Process — declarative (no Apex), guaranteed delivery with retry (every 2 hours for 24 hours). External system must acknowledge receipt. Modern alternative: Platform Events (more flexible, not SOAP-only).
🎤 One-Line Answer
"Outbound Messages send SOAP notifications to external endpoints with guaranteed delivery and auto-retry — declarative, no code. Modern alternative: Platform Events for more flexibility."
Q81
What is Salesforce Connect and External Objects?
✅ Direct Answer
Salesforce Connect enables real-time access to external system data via External Objects (__x suffix) — data never imported into Salesforce, always queried live. Supports OData 2.0/4.0, Cross-org, Custom adapters. External Objects support SOQL, reports, and related lists.
🎤 One-Line Answer
"Salesforce Connect queries external data live via External Objects (__x) — no import, no storage cost. Perfect for large ERP datasets that can't or shouldn't be copied into Salesforce."
Q82
What are the different deployment methods in Salesforce?
✅ Direct Answer
Four methods: Change Sets (declarative, sandbox to prod, no rollback), SFDX/Metadata API (source-controlled, CI/CD pipelines, rollback possible), Packages (1GP managed/unmanaged, 2GP second-gen for modular deployment), ANT Migration Tool (legacy XML-based scripted deployments).
🔑 Key Points for Interviewer
- Change Sets: most common for TCS admins — no version control
- SFDX: modern, Git-based, CI/CD — TCS enterprise standard
- Packages: ISV development and multi-org deployments
- ANT: legacy — being replaced by SFDX
- TCS uses SFDX + GitHub Actions for large projects
🎤 One-Line Answer
"Four methods: Change Sets (declarative, common), SFDX/Metadata API (source-controlled, CI/CD), Packages (ISV/modular), ANT (legacy). TCS enterprise projects use SFDX with Git version control."
Q83
What is Salesforce DX (SFDX) and how does it improve development?
✅ Direct Answer
SFDX is source-driven development using Scratch Orgs (temporary dev environments), Salesforce CLI, Git version control, and CI/CD pipelines. It replaces sandbox + change set deployment with proper DevOps — code lives in Git, not locked in a sandbox. Enables team development at enterprise scale.
🎤 One-Line Answer
"SFDX replaces sandbox + change set with Git workflow, Scratch Orgs, and CI/CD — enabling proper team development. Code in Git, not locked in sandbox, with automated testing on every commit."
Q84
What is the Composite API?
✅ Direct Answer
Composite API combines up to 25 REST API requests in one HTTP call — sequential execution with referenceId chaining (output of step 1 as input to step 2). Reduces round trips, saves API quota. allOrNone=true makes it transactional. Essential for creating related records in one HTTP call.
🌍 Real World Example
Create Account + Contact + Opportunity in one HTTP call: referenceId chaining links Contact.AccountId = @{Account.id} and Opportunity.AccountId = @{Account.id}. Without Composite: 3 round trips, risk of partial failure. With Composite + allOrNone=true: 1 call, either all succeed or all roll back.
🎤 One-Line Answer
"Composite API bundles 25 API calls in one HTTP request with referenceId chaining — saves API quota and latency. allOrNone=true makes it transactional (all succeed or all roll back)."
Q85
What is MuleSoft and how does TCS use it?
✅ Direct Answer
MuleSoft is Salesforce's enterprise integration platform connecting any system — ERP, databases, legacy, APIs — via hub-and-spoke architecture. Handles data transformation, error handling, retry logic, API management. TCS is one of the largest MuleSoft implementation partners globally, using it for all large enterprise integration projects.
🎤 One-Line Answer
"MuleSoft is Salesforce's enterprise iPaaS connecting any system via API-led connectivity (Experience/Process/System APIs). TCS uses it for all large integrations involving SAP, Oracle, and legacy systems."
🎯 Section 8 — Real-World Scenario Questions
Q86–Q100 · Advanced · TCS Manager Round Focus
Q86
SCENARIO: A trigger fires on Account update and creates Tasks. Users report duplicate Tasks being created. What is the root cause and fix?
✅ Direct Answer
Root cause: trigger recursion — trigger updates Account → fires trigger again → creates more Tasks. Fix: add static Boolean recursion guard. Also check if multiple automations (trigger + Flow + workflow) all creating Tasks for the same event. Audit all automations on the Account object.
🌍 Real World Example
Investigation at XYZ Company: Account trigger AND a Record-Triggered Flow BOTH creating Tasks on Account update. Fix: 1) Added recursion guard to trigger. 2) Removed duplicate logic from Flow. 3) Added entry condition to Flow (only when specific field changes). Duplicates stopped. Rule: always audit ALL automations on an object before adding new ones.
🎤 One-Line Answer
"Duplicate Tasks = trigger recursion or multiple automations doing same thing. Fix: static Boolean guard in trigger + audit all automations (trigger, Flow, Process Builder) on the object."
Q87
SCENARIO: A user reports they can see opportunities they shouldn't have access to. How do you investigate?
✅ Direct Answer
Investigate: 1) Check OWD for Opportunity — if Public, everyone sees everything. 2) Check if user's role is high enough in hierarchy to see those records. 3) Check sharing rules — any rule giving too broad access? 4) Check if user has "View All" on Opportunity. 5) Login As user to reproduce exactly. 6) Use "Why can I see this record?" tool.
🎤 One-Line Answer
"Investigate: OWD too open → Role Hierarchy too high → Sharing Rule too broad → View All permission. Login As user to reproduce. Use Lightning's 'Why can I see this?' tool for fastest diagnosis."
Q88
SCENARIO: Batch Apex is failing with CPU limit errors. How do you fix it?
✅ Direct Answer
Fix: reduce batch size (try 50-100), optimize SOQL in execute() (ensure selective queries), replace nested loops with Map-based O(1) lookups, move complex calculations to a separate Queueable from finish(). Use Limits.getCpuTime() to find the hotspot in execute().
🌍 Real World Example
// Root cause: nested loop = O(n²) complexity
// BAD: for each account, scan all contacts
for(Account a : scope) {
for(Contact c : allContacts) { // O(n) per account!
if(c.AccountId == a.Id) { /* process */ }
}
}
// FIX: Map = O(1) lookup
Map<Id, List<Contact>> contactMap = /* pre-built */;
for(Account a : scope) {
List<Contact> contacts = contactMap.get(a.Id); // O(1)
}
// Also: Database.executeBatch(new MyBatch(), 50); // Smaller chunks
🎤 One-Line Answer
"Reduce batch size, replace nested loops with Map-based lookups, use Limits.getCpuTime() to find hotspot, move post-processing to Queueable from finish()."
Q89
SCENARIO: TCS client wants to migrate 5 million Account records from legacy CRM to Salesforce. What is your strategy?
✅ Direct Answer
Strategy: 1) Add External ID field to Account (legacy system ID). 2) Export data from legacy CRM as CSV. 3) Clean and transform data (remove duplicates, fix formats). 4) Disable triggers/workflows during migration. 5) Use Data Loader with Bulk API 2.0 in batches of 200K. 6) Validate record counts and sample data. 7) Re-enable triggers. 8) Run parallel testing for 2 weeks.
🌍 Real World Example
TCS migration approach: Week 1 — data profiling and cleanup (remove 15% duplicates). Week 2 — trial load to sandbox, validate. Week 3 — production load (Friday night, 5 hours). Week 4 — parallel running (both systems live). External ID on all objects enables re-runnable upserts — safe to run multiple times without creating duplicates.
🎤 One-Line Answer
"External ID + Bulk API 2.0 Data Loader. Disable triggers during load. Phased approach: sandbox trial → production load → parallel running → cutover. Always upsert (not insert) for idempotency."
Q90
SCENARIO: A deployment from sandbox to production fails. What do you check?
✅ Direct Answer
Check in order: 1) Test coverage — production requires 75% minimum, all test methods must pass. 2) Missing dependencies — components in package that aren't in production yet. 3) API name conflicts — already exists in production with different definition. 4) Validation rule failures — test data not meeting production validation rules. 5) Check deployment error details carefully.
🎤 One-Line Answer
"Check: test coverage <75%, test failures, missing dependencies, API name conflicts, validation rule issues. Read deployment error log carefully — it tells you exactly which component and why."
Q91
SCENARIO: Client says the Salesforce page is loading very slowly. How do you diagnose and fix it?
✅ Direct Answer
Diagnose: 1) Browser DevTools Network tab — which component/API call is slowest? 2) Check LWC — multiple Apex calls on connectedCallback loading serially. 3) Check SOQL queries — are they selective? 4) Lightning Inspector Chrome extension for component profiling. 5) Check page components count — too many = too many parallel requests.
🌍 Real World Example
Account page taking 8 seconds: 5 LWC components each making separate Apex calls = 5 queries on load. Fix: combined 5 queries into one optimized Apex method + cacheable=true. Added SOQL indexes on queried fields. Load time: 8 seconds → 1.5 seconds. TCS performance optimization approach: measure first, then optimize.
🎤 One-Line Answer
"Diagnose with Lightning Inspector and Browser DevTools. Fix: combine Apex calls, add cacheable=true, optimize SOQL with selective queries and indexes, reduce components per page."
Q92
SCENARIO: Design a Salesforce solution for a client that needs approval for any Opportunity over ₹10 Lakhs.
✅ Direct Answer
Design: 1) Approval Process on Opportunity — entry criteria: Amount > 1,000,000 AND IsClosed = false. 2) Step 1: Sales Manager approves (up to ₹25L). Step 2: VP approves (above ₹25L). 3) Record locked during approval. 4) On Approval: Flow fires to update Stage, send congratulations email. 5) On Rejection: Flow resets Stage, notifies rep with reason.
🎤 One-Line Answer
"Multi-step Approval Process with entry criteria (Amount > 10L), manager/VP routing, record locking, and Flows triggered on approval/rejection for post-decision automation."
Q93
SCENARIO: You need to send Salesforce data to an ERP system whenever an Opportunity is Closed Won. Design the integration.
✅ Direct Answer
Design: Record-Triggered Flow (After Save) fires when Stage changes to Closed Won → publishes Platform Event. MuleSoft subscribes to Platform Event via CometD → transforms data to ERP format → calls ERP REST API. Advantages: async (user doesn't wait), decoupled (ERP down = events replay), auditable (Platform Event history).
🎤 One-Line Answer
"Flow detects Stage = Closed Won → publishes Platform Event → MuleSoft subscribes → calls ERP. Async, decoupled, resilient. If ERP is down, events replay when it recovers — no data loss."
Q94
SCENARIO: A report in Salesforce is showing wrong numbers. How do you troubleshoot?
✅ Direct Answer
Debug: 1) Check report filters — are they correct (date range, record type, status)? 2) Check running user — report respects their record access. 3) Check sharing settings — might be missing records due to OWD. 4) Check if formula fields are calculating correctly. 5) Export to CSV and validate against raw data. 6) Check if report type includes all needed records (e.g., "Accounts with Opportunities" excludes accounts without).
🎤 One-Line Answer
"Check: report filters correct, running user's record access, sharing settings, formula field logic, report type scope. Export to CSV to validate against raw data — numbers don't lie."
Q95
SCENARIO: TCS client has 3 business units all needing Salesforce. Single org or multiple orgs?
✅ Direct Answer
Recommend Single Org unless compliance requires isolation. Single Org: shared Account/Contact data, BU-specific Record Types and Permission Sets, sharing rules for BU isolation, centralized reports across BUs, lower TCO, one integration point. Multi-Org: full isolation, independent releases — only if regulatory/data sovereignty requires it.
🎤 One-Line Answer
"Single Org: shared data, lower cost, unified reporting, one integration point. Multi-Org: full isolation, independent releases. Recommend Single Org unless regulatory requirements mandate complete data isolation."
Q96
SCENARIO: How do you handle a situation where a trigger is causing "UNABLE_TO_LOCK_ROW" errors?
✅ Direct Answer
UNABLE_TO_LOCK_ROW = multiple concurrent transactions competing for same record lock (10-second timeout). Common cause: data skew — many child records under one parent all updating simultaneously, locking the parent. Fix: restructure data model (account hierarchy to distribute load), move trigger updates to async Queueable, add retry logic.
🎤 One-Line Answer
"UNABLE_TO_LOCK_ROW = concurrent transactions competing for same lock. Fix data skew (account hierarchy), move trigger updates to async Queueable, implement exponential backoff retry logic."
Q97
SCENARIO: How would you implement a Lead scoring system in Salesforce at TCS?
✅ Direct Answer
Design: 1) Custom Score__c field on Lead. 2) Before-save Flow calculates score based on: Industry match (+20), Company size (+15), Job title seniority (+25), Lead Source (+10), Email domain quality (+10), Form fill completion (+20). 3) Einstein Lead Scoring for AI-powered scoring. 4) Dashboard showing score distribution. 5) Assignment Rule: Score > 80 → route to senior SDR.
🎤 One-Line Answer
"Before-save Flow calculates score from multiple dimensions (industry, title, source, size). Einstein Lead Scoring for AI enhancement. High-score Leads routed to senior reps via Assignment Rules."
Q98
SCENARIO: A client wants to track all changes made to the Opportunity Amount field for audit purposes. How do you implement this?
✅ Direct Answer
Three approaches: 1) Field History Tracking (Setup → Object → Field History) — tracks last 18 months, shows Old Value/New Value/Changed By/Date, free and declarative. 2) Salesforce Shield Field Audit Trail — 10 years history, paid. 3) Custom audit object (Amount_Change_History__c) populated by After Trigger on Opportunity — unlimited history, searchable, reportable.
🎤 One-Line Answer
"Option 1: Field History Tracking (free, 18 months, declarative). Option 2: Shield Field Audit Trail (paid, 10 years). Option 3: Custom audit object via trigger (unlimited, fully reportable). Choose based on retention and cost requirements."
Q99
SCENARIO: Explain how you would onboard a junior Salesforce developer at TCS on a new project.
✅ Direct Answer
Onboarding plan: Week 1 — org walkthrough (data model, security, existing automations). Code review of existing Apex/LWC. Development standards document (naming conventions, trigger framework, test patterns). Week 2 — pair programming on first feature. Week 3 — independent small task with code review. Ongoing — PR reviews, Trailhead learning path, weekly 1-on-1.
🎤 One-Line Answer
"Structured onboarding: org walkthrough → standards documentation → pair programming → independent tasks with code review. Code review gates prevent bad code reaching production. Education over blame."
Q100
SCENARIO: TCS client wants to implement Salesforce for the first time. What are your first 5 steps?
✅ Direct Answer
First 5 steps: 1) Discovery — understand business processes, pain points, integrations, user roles (2-3 weeks). 2) Data Model Design — objects, relationships, external IDs (1 week). 3) Security Design — OWD, roles, profiles, permission sets (1 week). 4) Configure sandbox — declarative setup first (validation rules, layouts, reports). 5) User Acceptance Testing — real users testing real scenarios before go-live.
🌍 Real World Example
TCS greenfield implementation: Discovery with 15 stakeholders across sales, service, finance (2 weeks). Data model: 8 custom objects. Security: 12 profiles, 24 permission sets, OWD = Private for all sensitive objects. Sandbox config: 3 months. UAT: 6 weeks. Go-live: phased (Sales Cloud first, Service Cloud 3 months later). Total: 9 months. TCS follows this structured approach on every implementation.
🎤 One-Line Answer
"Discovery → Data Model Design → Security Design → Configure Sandbox → UAT. Never skip discovery — 80% of implementation problems come from unclear requirements in the first 2 weeks."
🔗 Continue Your Salesforce Interview Prep
🚀 Bookmark sfinterviewpro.com
1,200+ free Salesforce interview questions across 17 topics. No paywall. No signup. Updated weekly.
Browse All Topics →