Updating Salesforce with the Execute Anonymous Window
Jun 18, 2024Sometimes it's useful to be able to mass delete records in a sandbox.
I was doing some work for a client this week.
And they had me building an automation where, when one case record was created, between 3 and 12 more cases were also created as child records.
I was testing this out in a developer sandbox and I was generating lots of cases.
I hit a point where I wanted to start fresh from zero, but there were over 30 cases in the system.
One by one deletion was not appealing, but I did want to delete all the cases.
What to do?
Enter a bit of code into the developer console, that's what!
By opening the Developer Console and clicking Debug -> Open Execute Anonymous Window you can access a code editor that will run code directly in a Salesforce environment.
I wrote the following code:
List<Case> caseList = [SELECT Id FROM Case];
delete caseList;
And after pressing Execute the code ran.
In this scenario it deleted every case in developer the sandbox environment.
Perfect!
Tip: Be very careful not to run this in a production environment.
We could of course change which Cases were deleted by adding criteria to our SOQL query.
Below is another example showing how to only delete cases created TODAY.
List<Case> caseList = [SELECT Id FROM Case WHERE CreatedDate = TODAY];
delete caseList;
A similar approach can also be used to create records in a developer sandbox.
I often find (in a brand new developer sandbox) that its helpful to quickly create several records to test things out on.
Running the code below in the Execute Anonymous Window quickly creates 10 new accounts.
List<Account> accounts = new List<Account>();
for(Integer i = 0; i < 10; i++){
Account a = new Account();
a.Name = 'Test Account Number ' + i;
accounts.add(a);
}
insert accounts;
And voila!
Ten new accounts ready for testing in a brand new environment.
When I first learned how to use the Execute Anonymous Window I would only ever work with it in a sandbox environment.
I felt it was too risky to ever use in production (because it could delete production data).
I would recommend you follow the same course and only use it in developer sandboxes.
I also kept a notepad file with reusable code samples (like the three above) so that I could quickly create accounts or delete test records without needing to rewrite the code everytime.
And that's a wrap!
Today we covered how to quickly delete and create records in sandbox through the developer console, and some best practices for doing so.
Thanks for reading :)
Best,
Nick
SalesforceĀ Saturdays
Join the Salesforce Saturday newsletter. Every Saturday, you'll get 1 actionable tip on Salesforce technology or career growthĀ related to the Salesforce Industry.
We hate SPAM. We will never sell your information, for any reason.