ApexSensei

Drills › Change records (DML)

Insert a tagged Account

Change records (DML) · Beginner · 10 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A data-loading script must create one Account and confirm the exact row Salesforce saved.

Insert one uniquely tagged Account and verify the saved record by its assigned Id.

What you will learn

insert saves a new record and writes its new Id back onto the same variable. Before the insert, that Id is null. Query by the Id when you need proof from the database.

insert account;
Id savedId = account.Id;

Gotcha. DML normally saves for good. ApexSensei rolls back every run, so practice Accounts do not stay in your org.

The task

Insert one uniquely tagged Account and check the saved record by its new Id.

Examples:

  • before insert, the Account has no Id → Id before insert: null
  • after insert, Salesforce fills in the Id → Id assigned: true
  • a query by that Id finds the one saved row → Saved count: 1 and Name matches: true

Requirements:

  1. Print Id before insert: followed by account.Id, before you insert.
  2. Insert the Account once.
  3. Query Accounts only by the Id the insert gave it, for example WHERE Id = :account.Id.
  4. Print Id assigned:, Saved count: and Name matches: (does the saved Name equal tag?).

Starter code

String tag = 'AS-INSERT-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
Account account = new Account(
    Name = tag,
    Description = 'Created by ApexSensei'
);

List<Account> saved = new List<Account>();

When it passes

The Id is null before the insert and set after it, and a query by that Id returns one row whose Name matches the tag.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ SObject field access · Update a tagged Account ›