Salesforce

Anonymous Apex: The Execute Anonymous Window in Salesforce Developer Console

Execute Anonymous is one of those tools that every Salesforce developer uses from week one but rarely thinks about systematically. It runs Apex code directly in Developer Console — no class, no test class, no deployment — and it commits changes to the real database. It is the fastest way to test SOQL, fix data issues, and validate logic before putting it in production code. This article covers how it works, when to use it, how to read the debug output, and the patterns that make it genuinely useful rather than just a convenience.

What Execute Anonymous Actually Is

The Execute Anonymous window runs Apex in what Salesforce calls an "anonymous block" — code that is compiled and executed immediately in the context of the currently logged-in user. It is not saved, it does not have a class name, and it does not appear in your org's Apex class list. It just runs.

Because it runs as the logged-in user, it respects all sharing rules, field-level security, and object permissions for that user. If you are logged in as a System Administrator, you have full access. If you run it as a user with restricted permissions, your code will hit the same permission walls that user's production code would hit.

Governor limits apply fully. Each execution gets a fresh set: 100 SOQL queries, 150 DML statements, 50,000 rows retrieved, and 10MB heap. The limits reset per execution, not per session — every time you click Execute, the counter starts from zero.

How to Open It

Developer Console is available from the top-right gear icon in any Salesforce org: Setup icon → Developer Console. Once open, navigate to Debug → Open Execute Anonymous Window, or press Ctrl+E (Windows) / Cmd+E (Mac).

The window that opens has a text area for your code and two buttons: Execute (runs and collects logs) and Execute Highlighted (runs only the selected portion of your code). The latter is useful when you have a long block and only want to run part of it.

Below the code window, the log pane shows all debug output from your execution. You can filter by log category and level — for most workflows, setting USER_DEBUG at FINE is sufficient to see your System.debug() calls without wading through framework noise.

The Core Use Cases

1. SOQL Validation Before Writing a Class

The single most common use of Execute Anonymous is testing a SOQL query before embedding it in a trigger or class. Write the query, run it, check that it returns the right records, then copy the working query into your code.

List<Account> accounts = [SELECT Id, Name, Industry FROM Account WHERE Industry = 'Technology' LIMIT 10];
System.debug('Count: ' + accounts.size());
for (Account a : accounts) {
    System.debug(a.Name + ' | ' + a.Industry);
}

This lets you catch WHERE clause errors, field name typos, and unexpected result counts before they surface in production. Particularly useful when dealing with complex cross-object queries or aggregate functions.

2. Data Fixes

A targeted data fix — updating a field on a set of records, reassigning owner, clearing a field — is a common task in any Salesforce org. Anonymous Apex handles this faster and more precisely than a data loader CSV, especially when the selection logic is complex.

The correct pattern is: query first to confirm scope, fix one record with LIMIT 1 to test the update, then run on the full set:

// Step 1: Confirm scope
List<Contact> contacts = [SELECT Id, LeadSource FROM Contact WHERE LeadSource = null AND CreatedDate = TODAY];
System.debug('Records to fix: ' + contacts.size());

// Step 2: Update
for (Contact c : contacts) {
    c.LeadSource = 'Web';
}
update contacts;
System.debug('Done.');

Always verify the count before running the DML. A WHERE clause that returns 5,000 records instead of 50 is the kind of mistake that is much easier to prevent than to undo.

3. Testing Logic Before Writing a Test Class

If you have a calculation or a method you are about to build, run the logic in Execute Anonymous first. You get instant feedback on whether your approach works on real data before you invest in writing the class and test class:

// Test discount calculation logic
Opportunity opp = [SELECT Amount, StageName FROM Opportunity WHERE StageName = 'Closed Won' LIMIT 1];
Decimal discountedAmount = opp.Amount * 0.9;
System.debug('Original: ' + opp.Amount + ' | Discounted: ' + discountedAmount);

This makeshift test pattern — verify logic on real data first, then write the class — catches problems earlier and tends to produce cleaner final code because you know what edge cases actually exist in your data.

4. Debugging Triggers and Classes

When a trigger or class is behaving unexpectedly, run the relevant portion of the logic in Execute Anonymous to isolate whether the issue is in the logic itself or in how it is being called. You can also call methods from your existing Apex classes directly:

// Call your utility method directly
MyUtilityClass.processBatch(recordId);

Reading the Debug Log

After execution, the log pane shows the full debug output. The most relevant entries are prefixed with USER_DEBUG — these are your System.debug() calls. Each line shows:

  • Timestamp — milliseconds from execution start
  • Log category + level — USER_DEBUG | DEBUG
  • Line number — which line in your code produced this output
  • Value — whatever you passed to System.debug()

If execution fails, look for FATAL_ERROR or EXCEPTION lines. These will show you the exception type, message, and the line number where it occurred. For governor limit exceptions, you will see a LimitException with the specific limit that was exceeded.

You can also filter the log by category using the debug log level settings (Debug → Change Log Levels). Reducing framework log levels and keeping your own USER_DEBUG at FINE produces a cleaner, faster log that is easier to read.

Governor Limits in Practice

The same limits that apply in production apply in Execute Anonymous — but with one practical difference: each execution is its own transaction. If you need to perform more than 100 SOQL queries, split your operations across multiple Execute runs.

You can also check remaining limits programmatically:

System.debug('SOQL remaining: ' + Limits.getLimitQueries() - Limits.getQueries());
System.debug('DML remaining: ' + Limits.getLimitDmlStatements() - Limits.getDmlStatements());

For large data fixes — more than 10,000 records — Anonymous Apex is not the right tool. You will hit the 10,000-row DML limit. Use Batch Apex instead, which can be triggered from Execute Anonymous:

Database.executeBatch(new MyBatchClass(), 200);

What to Be Careful About

DML in Execute Anonymous is real. There is no sandbox rollback, no "preview mode," no confirmation step. An update statement that fires in Execute Anonymous updates the database permanently. This is why the query-first pattern matters — always confirm your scope before running any DML.

Anonymous Apex also triggers all normal automation: workflows, Process Builder flows, triggers. If your update fires a trigger that sends an email or updates other records, that will happen. Test first in a sandbox where possible, particularly for updates that touch high-volume objects.

Finally, remember that code in the Execute Anonymous window is not saved. If you write a useful data fix or validation script, save it somewhere — a note, a text file, a team repository of Apex snippets — before closing Developer Console.

The Workflow That Works in Practice

The most effective use of Execute Anonymous in a development workflow looks like this:

  1. Write and validate the SOQL query, confirming the right records and field values
  2. Build the logic incrementally, adding one piece at a time and checking debug output
  3. Run on a single record with LIMIT 1 before expanding to the full dataset
  4. Once the logic is confirmed, copy it into the Apex class and write the test class against known data
  5. Save useful snippets — data fix patterns, diagnostic queries — for reuse

Execute Anonymous is not a replacement for proper Apex development. Anything that runs regularly — triggers, scheduled jobs, batch processes — belongs in a class with a test class. What Execute Anonymous does is compress the feedback loop at the start of that process, letting you validate assumptions on real data before investing in the full development cycle.

← All articles