[SalesForce] Database.query() default sort order

Does a Database.query() result maintain the order of the WHERE clause list I'm searching by?

List<Id> myList = new List<Id>;
myList.add('My Opportunity 1');
myList.add('My Opportunity 2');
myList.add('My Opportunity 3');
String soql = 'SELECT FROM Opportunity WHERE Name IN (\'' + myList.get(0) + '\',\'' + myList.get(1) + '\',\'' + myList.get(2) + '\')';
List<Opportunity> myResult = Database.query(soql);

Is it valid that:

myResult.get(0).Name == 'My Opportunity 1'
myResult.get(1).Name == 'My Opportunity 2'
myResult.get(2).Name == 'My Opportunity 3'

Use case is I'm trying to build a deep cloning tool which accepts any record and clones all children, grand-children, great-grand-children, etc. Part of this method requires me to be able to identify which cloned grand-child is related to which original grand-child (so as to parent to the correct cloned great-grand-children). I would like to compare the input list with the output list and associate (0) with (0) and (1) with (1), but that only works if the Database.query() method maintains the same sort order.

One option is to create a field on all the objects that stores the "cloned from" ID, but this is far from ideal for a truly scalable cloning utility. I'd like to be able to dynamically associate the recently cloned&inserted records with their originals while traversing down the chain of children.

Best Answer

Almost certainly not; the order is undefined.

Perhaps a silly question, but why not add an order by clause? It sounds like, for your purposes, the order doesn't matter as long as it's consistent. You may be able to just order by id asc or createddate desc.

Related Topic