I want to update list of list of account. I am getting list of accounts from many sources, now i want to update them.

list<list<sObject>> la=new list<list<sObject>>();
upsert la;

Its throwing an error, is there any way through which we can upsert list of list of accounts?


You should instead look at the addAll method, which would allow you to use just one List<Account>:

List<Account> allRecords = new List<Account>();
upsert allRecords;

If, for some reason, you really want to maintain separate lists, you will have to flatten the structure you have in your OP:

List<Account> allRecords = new List<Account>();
for (List<Account> accountList : listOfLists)
upsert allRecords;

You can't do this. You can only DML on single records or lists. Instead, make a single list and use addAll:

Account[] records = new Account[0];
upsert records;

As a side note, you also can't upsert on a generic list of SObject, so you'll need to use the Account concrete type instead.

  • Well, you can upsert on a generic list, you just need to be more clever about it. – Adrian Larson Apr 28 '16 at 16:26
  • 1
    @AdrianLarson I've never been able to accomplish this or seen it done. How do you do this? – sfdcfox Apr 28 '16 at 16:29
  • I solved it here. The only caveat is that you can't do it if you want to do Database.upsert(List<SObject>, SObjectField, Boolean), because that throws a compile error instead of runtime. – Adrian Larson Apr 28 '16 at 16:30
  • 1
    @AdrianLarson You're still instantiating a concrete sobject collection, though. My point was that the original code as written would have crashed for a completely annoying reason. Still, that's a pretty nifty trick in a pinch. – sfdcfox Apr 28 '16 at 16:33
  • 1
    @AdrianLarson You're instantiating a List<SpecificSObjectType> by way of Type.forName, and boxing it inside a generic reference. It works because upsert tries to unbox the value to see if it's a concrete list type before throwing a runtime error. I just tried that out. The code as written by the OP used a generic list, which would compile but then fail with a runtime exception. Like I said though, it's nice to know that it's not a compile-time error, which lets us have some code reuse. In fact, I have a use for that in my current code base... – sfdcfox Apr 28 '16 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.