You need to sign in to do that
Don't have an account?
SOQL Query Record Order (w/ IN clause)
If I have a list of Account Ids that I want to run a query against, is there a way to get the Account records to be returned in the same order as in my original list? (My tests below fail. They seem to indicate that records are ordered by Id by default.)
public testMethod static void testOrderedListOfAccounts(){
Account a1 = new Account(name='A1 Account');
Account a2 = new Account(name='A2 Account');
Account a3 = new Account(name='A3 Account');
List<Account> newAccounts = new List<Account>{a1, a2, a3};
insert newAccounts;
/* order of accounts going in to the query is a3, a1, a2. */
List<Id> unorderedAccountIds = new List<Id>{a3.Id, a1.Id, a2.Id};
List<Account> returnedAccounts = [SELECT Id, Name
FROM Account
WHERE Id IN :unorderedAccountIds];
/* This query doesn't return in order either.*/
//List<Account> returnedAccounts =
//Database.query('SELECT Id, Name FROM Account WHERE Id IN (\'' +
// a3.Id + '\', \'' + a1.Id + '\', \'' + a2.Id + '\')');
/* This query doesn't return in order either.*/
//List<Account> returnedAccounts =
//Database.query('SELECT Id, Name FROM Account WHERE Id = \'' +
// a3.Id + '\' OR Id = \'' + a1.Id + '\' OR Id = \'' + a2.Id + '\'');
/* Verify order of Accounts is a3, a1, a2. */
System.debug('returnedAccounts[0] = ' + returnedAccounts[0]);
System.debug('returnedAccounts[1] = ' + returnedAccounts[1]);
System.debug('returnedAccounts[2] = ' + returnedAccounts[2]);
System.AssertEquals(a3.Id, returnedAccounts[0].Id); /* Test always fails here. */
System.AssertEquals(a1.Id, returnedAccounts[1].Id);
System.AssertEquals(a2.Id, returnedAccounts[2].Id);
}