Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
DictionaryAAnonymous Block, Apex
DevelopmentIntermediate

Anonymous Block, Apex

An Anonymous Block in Apex is a piece of Apex code that runs once without being saved to the org as a class, trigger, or scheduled job.

§ 01

Definition

An Anonymous Block in Apex is a piece of Apex code that runs once without being saved to the org as a class, trigger, or scheduled job. Developers run anonymous blocks to perform one-time tasks: cleaning up bad data, back-filling a new field on existing records, testing a snippet of logic, or initialising a Custom Setting. The block executes in the running user's context, with that user's permissions, sharing model, and governor limits. It does not persist after execution. Once the run finishes, the code is gone unless the developer copies it back into a class.

Anonymous Apex runs from several surfaces: the Developer Console's Execute Anonymous Window (Ctrl/Cmd-E), VS Code via the Salesforce CLI command sf apex run, Workbench's Apex Execute tab, or the REST API's executeAnonymous endpoint. Each surface produces the same outcome but exposes different debugging affordances. The Developer Console shows logs and limits inline. The CLI dumps the log to disk and is the path most production scripts use. The REST API returns a structured success/failure payload that automation can parse. Use of anonymous blocks is common for data migrations, post-deployment fix-ups, and ad hoc support work.

§ 02

How Anonymous Apex differs from saved code, and how to use it safely

How an anonymous block differs from a class or trigger

Saved Apex (classes, triggers, scheduled jobs, batch jobs) lives in metadata and runs whenever its trigger condition fires. An anonymous block exists only for one execution. It is not stored anywhere, has no test coverage requirement, and does not need to be deployed. The trade-off is that anonymous blocks are unaudited; once executed, the only record is the debug log generated during the run.

Run context, permissions, and sharing

An anonymous block runs as the user who launched it, including that user's profile, permission sets, and object/field permissions. Sharing rules apply unless the block declares without sharing at the script level (which Anonymous Apex does not support directly, since the block is not a class). To bypass sharing or run as a different user, wrap the logic in a helper class with the explicit sharing keyword and call the class method from the anonymous block.

Governor limits apply, with the same rules as a transaction

Each anonymous run is one Apex transaction and gets the same governor limits as any other synchronous Apex: 100 SOQL queries, 10,000 DML rows, 6 MB heap, and so on. For larger data fixes, structure the anonymous block to call Database.executeBatch on a one-off batch class. That moves the work into a batch context, which gets per-chunk limits and can handle millions of records.

Common use cases

Anonymous Apex is the right tool for: back-filling a new field on existing records, fixing a bad picklist value across thousands of records, bootstrapping Custom Settings or Custom Metadata Type values, kicking off a batch job, testing a snippet of logic before adding it to a class, and inspecting record data interactively. Most experienced Salesforce developers reach for it several times a week.

Debug logs and the Execute Anonymous Window

Every anonymous run produces a debug log if the user has the Apex Debug log level set. The Developer Console displays the log inline; the CLI writes it to a tmp file. System.debug calls inside the block surface in the log alongside SOQL queries, DML, and any thrown exceptions. The log is the only artifact left after a run, so add explicit System.debug lines for any value the script computes.

Running anonymous from the CLI and Workbench

The Salesforce CLI runs anonymous blocks with sf apex run --file path/to/script.apex. The output includes the log path. Workbench's Execute Apex tab supports the same content with an inline log viewer. Both surfaces are commonly used in production change windows because they leave a path-on-disk artifact that change tickets can attach.

Auditability and risk

Anonymous Apex is powerful and lightly audited. There is no test coverage requirement, no peer-reviewed metadata diff, and no automatic post-execution log retention. Production-grade orgs treat anonymous block execution as a privileged operation. The script is reviewed before running, the log is archived after, and the running user typically has a dedicated permission set that is added and removed for the change window.

When not to use anonymous blocks

Avoid anonymous Apex for recurring work; promote it to a scheduled batch class with proper test coverage. Avoid it for any change that should be reviewable later; the lack of metadata trail leaves no audit. Avoid it for anything that exceeds synchronous limits; convert to a batch class instead. And avoid it for any logic that should be unit-tested as part of a deployment pipeline; tests do not cover anonymous blocks.

§ 03

How to run an Anonymous Apex Block safely

Anonymous Apex is fast, powerful, and unaudited. Treat every production run as a controlled change: prepared script, peer review, retained log.

  1. Write the script in version control

    Create the .apex file in the repo, even if it will not be deployed. The file is the artifact that change reviews attach to and that future engineers can read.

  2. Peer-review the script

    Walk the script through a second engineer. Confirm DML counts, SOQL counts, and the records the script touches. Anonymous Apex does not have unit tests, so review is the only safety net.

  3. Run in sandbox first

    Execute the script in a representative sandbox. Inspect the resulting data and the debug log. Only after a clean sandbox run should production be considered.

  4. Execute in production with logging on

    Set the Apex debug log level to FINER. Run via the Developer Console, CLI, or Workbench. Watch for unexpected errors or limit warnings.

  5. Archive the log and the script

    Save the debug log and the .apex script to the change ticket or release record. Anonymous Apex leaves no audit trail; preserving these two files is the audit trail.

Gotchas
  • Anonymous Apex runs as the user who launches it, including their sharing model. To bypass sharing, wrap the logic in a without sharing class.
  • Governor limits apply identically to a synchronous transaction. Large data fixes must call a batch class, not run inline.
  • There is no test coverage requirement and no metadata trail. Audit logging falls on the operator, not the platform.
  • Errors silently fail unless explicitly caught. Use try/catch with System.debug to surface any failures in the log.
§

Trust & references

Sources

Cross-checked against the following references.

Official documentation

Straight from the source - Salesforce's reference material on Anonymous Block, Apex.

Keep learning

Hands-on resources to go deeper on Anonymous Block, Apex.

Was this entry helpful?
Help us write better definitions. Quick reactions or detailed edit suggestions.

About the Author

Dipojjal Chakrabarti is a B2C Solution Architect with 29 Salesforce certifications and over 13 years in the Salesforce ecosystem. He runs salesforcedictionary.com to help admins, developers, architects, and cert/interview candidates sharpen their fundamentals. More about Dipojjal.

§

Test your knowledge

Q1. What is an Anonymous Apex Block?

Q2. Which tool can you use to run an Anonymous Apex Block?

Q3. Why don't Anonymous Apex Blocks count toward code coverage?

§

Discussion

Loading…

Loading discussion…