Sub topic 7
Seeding with an Apex anonymous script
This chapter assumes you can read basic Apex, have the sf CLI authorized to a scratch org or sandbox, and know how Account and Contact relate through a lookup. Earlier chapters covered tree import. Here you create data with code instead.
When Apex is the right tool
An anonymous Apex script is a block of Apex that runs once, without being saved as a class in the org. It suits seed data when:
- Records need logic, such as loops, computed values, or related records built in one pass.
- You want the same triggers, flows, and validation rules that real users hit.
- The dataset is small, and a JSON plan file would be more effort than a short script.
Anonymous Apex is subject to governor limits, so it is a poor fit for thousands of rows. Use bulk commands for those.
A basic seed script
Save this as scripts/apex/seed.apex in your DX project.
Account acct = new Account(Name = 'Seed Account', Industry = 'Technology');
insert acct;
List<Contact> contacts = new List<Contact>();
for (Integer i = 1; i <= 5; i++) {
contacts.add(new Contact(
FirstName = 'Seed',
LastName = 'Contact ' + i,
AccountId = acct.Id
));
}
insert contacts;The script inserts the parent first. After insert acct, Apex fills in acct.Id, so the children can point to it directly. No reference IDs are needed, unlike in a plan file. The five Contacts go in with a single DML statement, which keeps you well inside the 150-statement limit.
Run it against your scratch org:
sf apex run --file scripts/apex/seed.apex --target-org my-scratchThe command prints compile errors or the runtime exception, and with --target-org omitted it uses your default org.
Making the script safe to rerun
Running the script twice creates duplicates. A simple guard checks for existing seed records first.
Integer existing = [SELECT COUNT() FROM Account WHERE Name = 'Seed Account'];
if (existing > 0) {
System.debug('Seed data already present, skipping.');
return;
}Put this at the top of the script. Anonymous Apex allows return at the top level. For a stronger guarantee, use an external ID field with upsert, covered in the next chapter.
Common errors
- Required field missing: the insert fails with
REQUIRED_FIELD_MISSING. Add the field to the script. - Validation rule or trigger failure: the whole statement rolls back. Read the message, then supply compliant values.
- Metadata not deployed: referencing a custom field that doesn't exist causes a compile error. Deploy the project before running the script.
- Too many DML statements or SOQL queries: this happens when you insert inside a loop. Collect records in a list and insert once.
Exercise
Exercise
Your seed script inserts 200 Contacts by calling insert inside a for loop, and it fails with a governor limit error. What change fixes it, and why?
Show answer
Add each Contact to a List<Contact> inside the loop, then call insert once after the loop. DML statements are limited per transaction, and a loop with one insert each uses a statement per record, while one bulk insert uses a single statement.