100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Common Apex Pitfalls

The recurring bugs — unbulkified loops, hardcoded Ids, recursive triggers, and swallowed exceptions — that cause most Apex production incidents.

PracticeIntermediate9 min readJul 10, 2026
Analogies

Common Apex Pitfalls

Most production Apex incidents trace back to a small set of well-known pitfalls: unbulkified DML/SOQL, hardcoded IDs, recursive triggers, and swallowed exceptions. These bugs are especially dangerous because they often pass code review and unit tests written against tiny datasets, then fail silently or catastrophically once real data volume, multiple triggers, or workflow automation interact in production. Recognizing these patterns during code review is one of the highest-leverage skills an Apex developer can build.

🏏

Cricket analogy: A batsman who's only faced net bowlers at medium pace has no idea how they'll cope with a genuine 150kph yorker in a World Cup final — Apex bugs that never show up against tiny test data appear only under real match pressure.

SOQL and DML Inside Loops

The single most common pitfall remains placing a SOQL query or DML statement inside a for loop that iterates over Trigger.new or a list of records — this passes code review because reviewers eyeball the logic, not the transaction context, and it passes a naive unit test that inserts one record. The failure only surfaces when someone performs a bulk operation like a Data Loader update of 5,000 records or a mass workflow-triggered update, at which point Salesforce throws System.LimitException: Too many SOQL queries: 101 and the entire transaction rolls back, including any legitimate changes.

🏏

Cricket analogy: Sending a fresh runner to the boundary rope to fetch a new ball after every single delivery instead of keeping spares in the umpire's pocket would grind a Test match to a halt — a SOQL query per loop iteration grinds a bulk transaction to a halt the same way.

apex
// BAD: SOQL inside loop
for (Opportunity opp : Trigger.new) {
    Account acc = [SELECT Id, Rating FROM Account WHERE Id = :opp.AccountId];
    if (acc.Rating == 'Hot') {
        opp.Probability = 90;
    }
}

// GOOD: bulkified
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
    accountIds.add(opp.AccountId);
}
Map<Id, Account> accountsById = new Map<Id, Account>(
    [SELECT Id, Rating FROM Account WHERE Id IN :accountIds]
);
for (Opportunity opp : Trigger.new) {
    Account acc = accountsById.get(opp.AccountId);
    if (acc != null && acc.Rating == 'Hot') {
        opp.Probability = 90;
    }
}

Hardcoded IDs and Recursive Triggers

Hardcoding a Record Type Id, Profile Id, or Queue Id directly as a string literal works in the sandbox where it was copied from but breaks the moment the code is deployed to production or another sandbox, because Salesforce generates different Ids per org — the correct approach is querying by DeveloperName via Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName(). Recursive triggers occur when an update inside a trigger causes the same trigger to fire again on the same records within the same transaction, which can create infinite loops or duplicate side effects like doubled email notifications; the standard fix is a static Boolean class variable that's checked and set at the top of the handler so re-entrant execution is skipped.

🏏

Cricket analogy: Writing a specific stadium's pitch report into a team's permanent strategy playbook, then using that exact playbook at a completely different ground, would misfire badly — hardcoding a sandbox's Record Type Id and using it in production misfires the same way because the Id doesn't exist there.

Never copy a Record Type, Profile, or Queue Id string literal from a sandbox URL into Apex code. Query it dynamically by DeveloperName using Schema describe methods — Ids are not portable across Salesforce orgs.

Ignoring Sharing Rules and Exceptions

An Apex class without 'with sharing' declared runs in system context by default, meaning it ignores organization-wide defaults, sharing rules, and role hierarchy — this is a real security pitfall because a controller powering a Visualforce page or LWC could inadvertently expose records a user shouldn't see. Equally dangerous is catching an exception with an empty catch block, which silently swallows the error and lets execution continue as if nothing failed, hiding bugs that then surface as confusing data inconsistencies weeks later instead of a clear stack trace at the point of failure; best practice is to log via a custom logging object or re-throw after handling.

🏏

Cricket analogy: A ground that lets any spectator walk onto the pitch without checking their ticket zone is like an Apex class without 'with sharing' — it ignores the access controls that were supposed to restrict who sees what.

  • The most common Apex bug is a SOQL query or DML statement placed inside a for loop over Trigger.new, which exceeds governor limits under bulk operations.
  • Never hardcode Salesforce Ids (Record Type, Profile, Queue) as string literals — query by DeveloperName instead, since Ids differ per org.
  • Recursive triggers happen when a DML update inside a trigger re-fires the same trigger on the same records; guard against it with a static Boolean flag.
  • Classes without 'with sharing' run in system context and bypass org-wide defaults and sharing rules — a security risk for user-facing code.
  • Empty catch blocks silently swallow exceptions and hide bugs; always log or re-throw instead.
  • Unit tests written only against a single record will not catch bulk-related governor limit failures.
  • Code review should specifically check for SOQL/DML in loops, hardcoded Ids, and missing sharing declarations.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#ApexSalesforceStudyNotes#CommonApexPitfalls#Common#Apex#Pitfalls#SOQL#StudyNotes#SkillVeris#ExamPrep