Find your content:

Search form

You are here

Id assignment when creating sObjects in code


I'd like to get straight exactly what is happening when I create an sObject in code but can't find any information on the specifics.

The Id is null until after the DML insert statement. Does this mean that the Id is being assigned as a result of a return value from the database?

This leads me to wonder if I could get more than one value back from the insert.

Is it possible to insert and then select back all of the automatically created fields such as Case.CaseNumber in one statement? Or is the sequence below (a DML insert followed by a SOQL SELECT to get specific fields) the only / correct way to do this?

Case c = new Case();

System.assert(c.Id == null);         // id not created on Case construction
System.assert(c.CaseNumber == null); 

insert c;

System.assert(c.Id != null);         // not null after insert
System.assert(c.CaseNumber == null); // still null after insert

c = [SELECT Id, CaseNumber FROM Case WHERE Id = :c.Id];

System.assert(c.Id != null);
System.assert(c.CaseNumber != null); // not null after select from database

Attribution to: Joe

Possible Suggestion/Solution #1

Yes the id is set on the sobject instance after the insert invocation, however none of the other fields are automatically available. (Unless youve explicitly set them on the sobject and they are not calculated fields) So whilst you can directly obtain the id from the sobject instance, for anything else, you will have to execute a soql query to select those fields, as you have in your example above.

Here's an excerpt from the documentation

The insert statement automatically sets the ID value of all new sObject records. Inserting a record that already has an ID—and therefore already exists in your organization's data—produces an error.

Attribution to: techtrekker

Possible Suggestion/Solution #2

As techtrekker said, you cannot provide ID while you insert a record. It will be created automatically by Salesfrce.

In Salesforce, the formula field/auto number field will be calculated only when a SOQL/SOSL query is executed.

That is the reason the CaseNumber field is null until SOQL query is executed.

The above method is the right way to go!

Attribution to: Priyanka
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content