We're using SOSL to search Account and Contact objects and facing an issue. Records are returned in a variable of type List<List<sobject>> say searchList

I'm using this variable(searchList), to find specifically just Account records using following code :

  Account[] searchAccounts =  (Account[])searchList[0];
                    for(Account a :searchAccounts ){
 System.debug('AccountIdsInitial='+accountIdsIni );

Now I print both searchList and searchAccounts variables. I'm finding Account records are returned in different order(sort) as shown below: enter image description here

If you see, record(as highlighted in yellow) in debug log come first in SOSL variable but same record came on 4th number, when I separately printed the list of Accounts listed.

Please suggest if this is an expected behavior !!

  • 6
    What is the type of accountIdsIni?
    – David Reed
    Oct 7, 2019 at 15:18

1 Answer 1


I'm assuming based on the observed behavior that accountIdsIni is typed as a Set<Id>. A Set is

an unordered collection of elements

The iteration order of a set

is deterministic, so you can rely on the order being the same in each subsequent execution of the same code.

but that doesn't mean that it's defined to be any specific order, or that the order of elements printed by System.debug() is guaranteed to be the same as the iteration order.

If you want an ordered collection, use a List.

  • Thanks David. 'accountIdsIni' is of type Account[] as shown in above code snippet . Let me try with list and revert.. thanks again !! Oct 8, 2019 at 8:01
  • @curious_techy I think something is confused here. You're adding values of type Id to accountIdsIni, so it can't be of type Account[].
    – David Reed
    Oct 8, 2019 at 15:28
  • Good Catch. Sorry. accountIdsIni is of type Set and that was causing problem. Once i change it to 'List'. things worked fine. Thanks for your excellent support!! Oct 8, 2019 at 16:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .