function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kunagu Varun Kumar SrinivasaraoKunagu Varun Kumar Srinivasarao 

Apex DML Selecting fields

I'm new to Apex and I stumbled upon this. I've a custom object named Cast which has a Rating field. I wanted to update all the Rating values to 3. I selected the Id field and updated all of them.
User-added image

I've a similar problem in which I want to update birth date field of all records where birth date is > 2000. This is my code. However I'm getting an exception SObject row was retrieved via SOQL without querying the requested field:

If I include Birthdate__c field in my query, the error goes away.
List<Person__c> listPersons = [SELECT Id FROM Person__c WHERE BirthDate__c > 2000-01-01];
for(Person__c person : listPersons){
	person.BirthDate__c = person.BirthDate__c.addYears(-100); 
}

try{
 Update listPersons;   
}
catch(DMLException ex){
    System.debug(ex.getMessage());
}
Why is that in my first code sample to update Rating field I was able to do that without selecting itin my query but why do I have to select Birthdate field for my second code?
 
Danish HodaDanish Hoda

Hi Varun,
This is because of the line inside the for-loop:
person.BirthDate__c = person.BirthDate__c.addYears(-100);

The operation includes person.BirthDate__c which needs to be queried well before.

Kunagu Varun Kumar SrinivasaraoKunagu Varun Kumar Srinivasarao
But in my first code snippet to update Rating field, I didn't query that before. How is it different from the birthdate update operation? In both the cases there is some assignment done to a field that is not selected as part of the query. I just couldn't understand why an error for the second one and why not for the first?
Danish HodaDanish Hoda
You are updating one of the fields (Rating__c) in the first scenario but in the second scenario - you are doing an operation on a field (BirthDate__c) which requires it to be queried.
Kunagu Varun Kumar SrinivasaraoKunagu Varun Kumar Srinivasarao
okay. Thank you