Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
Full Anonymous Block, Apex entry
How-to guide

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.

By Dipojjal Chakrabarti · Founder & Editor, Salesforce DictionaryLast updated May 19, 2026

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.

See the full Anonymous Block, Apex entry

Anonymous Block, Apex includes the definition, worked example, deep dive, related terms, and a quiz.