Skip to main content

Can someone explain what will happen when this Apex code runs? Will it update the Account successfully, or throw an error? Why?

Account acc = [

SELECT Id, Name

FROM Account

LIMIT 1

];

acc.Name = 'Updated Account';

List<Account> accounts = new List<Account>{ acc };

for (Account a : accounts) {

a.Name = 'Final Account';

}

update acc;

update accounts;Will both update statements execute successfully

#Apex

4 respostas
  1. Ontem 05:39

    Hi @Pranjal Budhlakoti

     

    The first update acc; will execute successfully.

    acc and accounts[0] reference the same Account record. The loop changes the Name to 'Final Account', so the first update saves 'Final Account'

     

    The second update accounts; will also execute successfully because it is a separate DML statement containing only one record. The Duplicate id in list error occurs when the same record ID appears multiple times in the same list being updated, not simply because the record is updated twice in separate DML statements.

    So, the final Account Name will be 'Final Account'.

    For Reference: Salesforce Apex DML documentation.  

     

    Hope This Helps!!.

0/9000