The 10 Apex Errors Every Developer Hits, and How to Fix Each
It works in the sandbox. It works when you save one record. Then a data load runs, an integration fires 200 updates at once, or a second automation lands on the same object, and the log fills with Too many SOQL queries: 101. Most Apex errors aren't mysterious. They're the same ten problems, showing up again.
This guide takes each one in turn: the exact message you'll see, why the platform throws it, a before-and-after code fix, and the gotcha that catches experienced developers. Every limit and behaviour has been checked against the current Apex Developer Guide (Winter '27, API version 68.0). Jump straight to the error that's ruining your day, or read top to bottom. The first four are governor limits, and they share one root cause.
Before You Start: Two Facts About Governor Limits
First, you can't catch a limit exception. The Execution Governors and Limits page is explicit: when code exceeds a limit, the governor throws a runtime exception that can't be handled. A try/catch around the loop does nothing, and the whole transaction rolls back. The fix is always in the design, never in error handling.
Second, limits belong to the transaction, not to your class. Every trigger, flow, managed package and workflow that runs in the same save shares the same budget. The class named in the error is simply whoever asked for the 101st query. Before you rewrite it, open the debug log, find the LIMIT_USAGE_FOR_NS and cumulative usage lines, and see who spent the budget.
| Per-transaction limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries issued | 100 | 200 |
| Records retrieved by SOQL | 50,000 | 50,000 |
| DML statements issued | 150 | 150 |
| Records processed by DML | 10,000 | 10,000 |
| Maximum CPU time | 10,000 ms | 60,000 ms |
| Total heap size | 6 MB | 12 MB |
| Stack depth for recursive trigger calls | 16 | 16 |
Source: Apex Developer Guide, Execution Governors and Limits. Scheduled Apex is asynchronous but runs with synchronous limits.
1. Too Many SOQL Queries: 101
The number is the query that broke the limit, not an error code. Synchronous Apex gets 100 SOQL queries per transaction (200 when asynchronous), and the 101st one throws. Nine times out of ten there's a query inside a for loop. It runs fine when a user saves one record, then fails the first time a data load sends 200 records through the trigger.
Before one query per record:
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
Account a = [SELECT Industry FROM Account WHERE Id = :c.AccountId]; // 200 records = 200 queries
c.Description = a.Industry;
}
}After one query for the whole batch, then a map lookup:
trigger ContactTrigger on Contact (before insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) accountIds.add(c.AccountId);
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accounts.get(c.AccountId);
if (a != null) c.Description = a.Industry;
}
}
This is the pattern Trailhead's Bulk Apex Triggers unit teaches: collect the IDs, query once with IN, and work from a map. When you need children, a single parent-child subquery often replaces a loop of queries entirely.
Database.query, Database.countQuery and Database.getQueryLocator all count, and so does every Get Records element in a record-triggered flow on the same object. A helper method called once per record is still a query in a loop, just one call away. Use Limits.getQueries() in a debug statement to see where the count climbs.
2. Too Many DML Statements: 151
The same mistake, on the write side. You get 150 DML statements per transaction, and every insert, update or delete counts as one, whether it carries one record or 10,000. So the fix is to stop writing inside the loop: collect the changes in a list and write once.
// Before: one update per opportunity
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
update o;
}
// After: one statement, many rows
List<Opportunity> toUpdate = new List<Opportunity>();
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
toUpdate.add(o);
}
update toUpdate;Writing to several objects? Keep one list per object type and write each once at the end of the handler. A "unit of work" class that collects changes and commits them in one place makes this the default rather than something each developer has to remember.
Database.setSavepoint() and Database.rollback() both count toward the DML statement limit, and in tests every System.runAs call counts too. Publishing platform events with EventBus.publish is also on the list.
3. Too Many Query Rows: 50001
This one surprises people because they only wrote one query. The 50,000-row limit is the total across every query in the transaction, including rows from parent-child subqueries. It usually means an unfiltered query that was fine when the org was small, such as all open cases or all contacts for an industry, has quietly grown past the line.
Pick the fix that matches what you actually need:
- You need a number, not records. Use
COUNT()or an aggregate query instead of loading rows and calling.size(). - You need some records. Add a selective
WHEREclause (ideally on an indexed field) and aLIMIT. - You genuinely need all of them. Move the work to Batch Apex. A batch's
Database.QueryLocatorcan return up to 50 million records, and limits reset for each chunk theexecutemethod processes.
// Before: loads every open case just to count them
Integer openCases = [SELECT Id FROM Case WHERE IsClosed = false].size();
// After: the database does the counting, and you get one row back
Integer openCases = [SELECT COUNT() FROM Case WHERE IsClosed = false];Database.getQueryLocator has an even lower cap of 10,000 rows per transaction.
4. Apex CPU Time Limit Exceeded
You get 10 seconds of application-server CPU time synchronously, 60 seconds asynchronously, shared by your Apex and everything else on the app server in that save, including flows and managed-package code. Time the database spends running SOQL and DML doesn't count, and neither does waiting on a callout. So this error is about computation, not slow queries, and the class it names is often not the one that spent the time.
The usual culprits are nested loops (replace them with a map lookup), several automations stacked on one object, and triggers that recurse into themselves:
// Before: O(n × m)
for (Contact c : contacts) {
for (Account a : accounts) {
if (a.Website == c.Website__c) { c.AccountId = a.Id; }
}
}
// After: O(n + m)
Map<String, Id> accountByWebsite = new Map<String, Id>();
for (Account a : accounts) { accountByWebsite.put(a.Website, a.Id); }
for (Contact c : contacts) {
Id match = accountByWebsite.get(c.Website__c);
if (match != null) c.AccountId = match;
}5. MIXED_DML_OPERATION
Some objects control who can see what: User, UserRole, Group, GroupMember, PermissionSetAssignment, QueueSObject and the territory objects among them. Salesforce calls these setup objects, and the sObjects That Can't Be Used Together in DML Operations page explains that you can't mix DML on them with DML on regular records in one transaction, because changing access mid-transaction could let operations run with the wrong permissions.
The classic case: a trigger creates an Account, then assigns the owner a permission set. The fix is to move one side into a separate transaction, usually with a Queueable or @future method.
public class OnboardingService {
public static void onboard(Account acct, Id userId, Id permSetId) {
insert acct; // non-setup object
System.enqueueJob(new AssignPermSet(userId, permSetId)); // setup object, new transaction
}
}
public class AssignPermSet implements Queueable {
private Id userId; private Id permSetId;
public AssignPermSet(Id userId, Id permSetId) {
this.userId = userId; this.permSetId = permSetId;
}
public void execute(QueueableContext ctx) {
insert new PermissionSetAssignment(AssigneeId = userId, PermissionSetId = permSetId);
}
}
In test classes, the error shows up when you create a user with a role and then insert test records. Per Mixed DML Operations in Test Methods, wrapping the setup-object DML in a System.runAs block avoids it.
UserRoleId, IsActive, ProfileId or Username, and the user isn't part of a Lightning Sync or Einstein Activity Capture configuration. Also note that mixed DML validation is skipped during deployment, so a test can pass on deploy and fail when you run it in the UI.
6. UNABLE_TO_LOCK_ROW
When a transaction writes a record, Salesforce locks it until the transaction ends. Another transaction that wants the same record waits, and after 10 seconds it gives up and throws this error, as the Help article Unable to lock row - Record currently unavailable describes. It's not a bug in your code so much as two pieces of work colliding.
The twist is that the locked record is often not the one you're updating. Saving a child record can lock its parent: a detail record in a master-detail relationship locks the master, and roll-up summaries and triggers that touch the parent do the same. So two Bulk API batches updating different Opportunities on the same Account can still fight over that Account.
Fixes, from cheapest to most involved:
- Sort data loads by parent ID so children of the same parent land in the same batch.
- Use smaller batches, or serial mode in the Bulk API so batches don't run in parallel against the same parents.
- Shorten the transaction. Locks are held until commit, so a slow trigger holds them longer. Every fix for error 4 helps here.
- Retry. Salesforce's record-level locking guidance notes that locks are held briefly, so retry logic in integrations handles occasional collisions. For frequent ones, sequence the work instead.
- Spread out "hot" parents. One Account with tens of thousands of children is a lock magnet. Distribute children across several parents.
When your own code must read and then update a record safely, lock it up front with FOR UPDATE:
// Lock the counter row so two transactions can't hand out the same number
Invoice_Counter__c counter = [
SELECT Id, Next_Number__c FROM Invoice_Counter__c LIMIT 1 FOR UPDATE
];
counter.Next_Number__c += 1;
update counter;FOR UPDATE can't be combined with ORDER BY, and locks it obtains are released automatically when you make a callout. Lock only what you must, and always lock records in the same order everywhere to avoid deadlocks. In tests, this error often comes from parallel test runs inserting portal or community users at the same time (see the Help article on UNABLE_TO_LOCK_ROW when running test classes).
7. You Have Uncommitted Work Pending
Apex won't let you call an external system while the transaction holds uncommitted DML. If the callout hung for 120 seconds, the database work and its locks would hang with it. The rule is simple: within one transaction, callouts first, DML after.
Three ways to restructure:
- Reorder. If you can, make the callout first, then write the response.
- Split it. Do the DML, then enqueue a Queueable that implements
Database.AllowsCallouts. It runs in its own transaction after yours commits. This is also the only option from a trigger, since triggers can't call out synchronously. - Decouple it. Publish a platform event and let a subscriber make the callout.
public class SyncOrderJob implements Queueable, Database.AllowsCallouts {
private Id orderId;
public SyncOrderJob(Id orderId) { this.orderId = orderId; }
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:ERP_Orders/orders/' + orderId);
req.setMethod('POST');
HttpResponse res = new Http().send(req); // callout first
update new Order(Id = orderId, ERP_Status__c = String.valueOf(res.getStatusCode())); // DML after
}
}
// In the service that saved the order:
insert order;
System.enqueueJob(new SyncOrderJob(order.Id));Database.releaseSavepoint(), and then call out. If any DML is still pending after the release, you still get this error, and an unreleased savepoint gives a different one: "All active Savepoints must be released before making callouts." In test methods, put DML before Test.startTest() and the mocked callout after it.
8. List Has No Rows for Assignment to SObject
Assigning a query straight to a single sObject variable tells Apex "there is exactly one". When zero rows come back (the record was deleted, the filter missed, or the running user can't see it under sharing), Apex throws. Two or more rows throw too, with a different message.
// Before: throws if no account matches
Account acct = [SELECT Id, Name FROM Account WHERE Id = :recordId];
// After, option A: query into a list and check
List<Account> results = [SELECT Id, Name FROM Account WHERE Id = :recordId LIMIT 1];
Account acct = results.isEmpty() ? null : results[0];
// After, option B: the safe navigation operator returns null instead of throwing
String name = [SELECT Name FROM Account WHERE Id = :recordId]?.Name;
Option B comes from the Safe Navigation Operator docs: on a single-row query, ?. evaluates to null when nothing comes back. It's tidy for reading one field. When you need the whole record or want to handle "not found" explicitly, option A is clearer.
with sharing class running as a sales rep may get zero rows for a record that definitely exists.
9. Attempt to De-reference a Null Object
You called a method or read a field on something that was null. In Salesforce code, the null usually comes from one of four places: a Map.get() for a key that isn't there, an empty lookup field (c.Account.Name when the contact has no account), Trigger.old or Trigger.oldMap in an insert context, or a collection that was declared but never initialized.
// Before: fails when the contact has no account, or the account has no owner
String ownerName = contact.Account.Owner.Name.toUpperCase();
// After: safe navigation short-circuits to null, ?? supplies a default
String ownerName = contact.Account?.Owner?.Name?.toUpperCase() ?? 'UNASSIGNED';
// Maps: check before you use
Account parent = accountsById.get(c.AccountId);
if (parent != null) { c.Description = parent.Industry; }
// Collections: initialize at declaration
List<Task> tasks = new List<Task>(); // not: List<Task> tasks;
The safe navigation operator ?. stops the chain and returns null instead of throwing, and the null coalescing operator ?? returns its right-hand side when the left is null. Together they replace most nested if (x != null) blocks.
?. everywhere to make the error go away. If a value should never be null, a silent null just moves the bug further from its cause. Use null-safe operators where null is a valid state (an optional lookup), and fail loudly with a clear message where it isn't.
10. SObject Row Was Retrieved via SOQL Without Querying the Requested Field
A queried record only carries the fields you selected. As Working with SOQL and SOSL Query Results puts it, reading any other field (apart from Id) is a runtime error, even if the field has a value in the database. The error message tells you exactly which field is missing, which makes this the easiest fix on the list.
// Before
Account a = [SELECT Id, Name FROM Account WHERE Id = :accId];
if (a.Industry == 'Banking') { ... } // Industry was never selected
// After
Account a = [SELECT Id, Name, Industry FROM Account WHERE Id = :accId];It gets harder when the query and the field access live in different classes. A service queries Accounts for one purpose, passes them on, and a second method reads a field the first never needed. Make the method that reads the fields own the query, or keep the field list in one shared selector method so every caller gets the same set.
Trigger.new have all their own fields, but not related ones. c.Account.Name in a Contact trigger is null, not an error, because the relationship isn't loaded. Query the parent explicitly, as in the fix for error 1.
Three Honourable Mentions
- Maximum trigger depth exceeded. Apex that fires triggers recursively can go 16 levels deep. A trigger that updates its own object with no guard hits this fast. Guard it with a static
Set<Id>of records already processed, rather than a single static Boolean that wrongly skips later chunks of 200. - Apex heap size too large. The heap is 6 MB synchronous and 12 MB asynchronous. Query only the fields you need, use SOQL for loops for large result sets, and clear big collections you've finished with.
- Record is read-only. You tried to change a field on
Trigger.newin an after trigger. Set field values in a before trigger, which saves without any DML at all.
Cheat Sheet
| Error | Usual cause | First fix to try |
|---|---|---|
| Too many SOQL queries: 101 | Query inside a loop | Collect IDs, query once with IN, use a map |
| Too many DML statements: 151 | DML inside a loop | Add to a list, write once |
| Too many query rows: 50001 | Unfiltered query on a growing object | COUNT(), selective WHERE, or Batch Apex |
| Apex CPU time limit exceeded | Nested loops, stacked automation, recursion | Maps, entry conditions, move to async |
| MIXED_DML_OPERATION | Setup and non-setup DML together | Queueable or @future; System.runAs in tests |
| UNABLE_TO_LOCK_ROW | Concurrent writes, often to a shared parent | Sort by parent, smaller or serial batches, retry |
| Uncommitted work pending | Callout after DML | Callout first, or Queueable with AllowsCallouts |
| List has no rows for assignment | Single-row query found nothing | Query into a list, or use ?. |
| Attempt to de-reference a null object | Missing map key, empty lookup, uninitialized list | Check for null; ?. and ?? where null is valid |
| SObject row retrieved without the field | Field not in SELECT | Add it; centralize field lists |
Official Resources
Straight from Salesforce: the docs this article is based on.
Trailhead
Developer Docs
- Execution Governors and Limits Apex Developer Guide · errors 1–4
- SOQL For Loops Apex Developer Guide · heap and chunking
- sObjects That Can't Be Used Together in DML Apex Developer Guide · mixed DML
- Mixed DML Operations in Test Methods Apex Developer Guide · System.runAs
- Locking Statements Apex Developer Guide · FOR UPDATE
- Record-Level Locking Data access & locking guide
- Transaction Control Apex Developer Guide · savepoints and callouts
- Safe Navigation Operator Apex Developer Guide · errors 8 and 9
- Working with SOQL and SOSL Query Results Apex Developer Guide · error 10
Salesforce Help
- Unable to lock row - Record currently unavailable Knowledge article · scenarios and fixes
- UNABLE_TO_LOCK_ROW when running test classes Knowledge article · parallel tests
- Proactive Alert Monitoring: Rowlock Timeout Errors Knowledge article · investigating lock alerts
- 'You have uncommitted work pending' error Knowledge article · callouts after DML
Same Apex errors showing up in your org week after week?
Book a code and automation review with our architects to find the root causes and fix them for good.
All information in this article was collected from publicly available resources, including official Salesforce documentation.