Let's say, I wrote a query that selects only Id field of an Object.

Why inside of the for loop I can select a field which wasn't queried and successfully update it, but I can't use this (unqueried field) inside if clause condition of inside for loop?

Why it works this way?

  • Does salesforce.stackexchange.com/questions/382048/… answer your question Commented Aug 5, 2022 at 6:14
  • @SaiPraveenKakkirala well not quite... I know how it works, I just wanted to know the logic behind it... like why you can do DML operations on it even though you didn't query it, but you can't select it inside, for example, for loop.... Commented Aug 5, 2022 at 6:23
  • 1
    In the one case you are assigning a value and in the other you are using the value. You can always assign a value to any SObject field so as to perform a DML. The attempt to use a field that wasn't queried generates an error to help you get your logic right - it is unlikely you want to use an unqueried field's value in logic since it would always be null, even when that isn't the case in the database. Thus you would get incorrect logic behaviour compared with the state in the database.
    – Phil W
    Commented Aug 5, 2022 at 6:38
  • 1
    In order to read field's data you must query it (otherwise you have nothing to read), while if you want to set it, you don't need to query it, because you're going to overwrite it. That rule is always enforced, it really doesn't matter in which code block: inside a loop, inside an if clause, or something else.
    – RubenDG
    Commented Aug 5, 2022 at 9:00
  • Thank you @PhilW and RubenDG for elaborating it. Yes now I understand the logic behind it Commented Aug 5, 2022 at 9:22


Browse other questions tagged .