[SalesForce] How Order By Id works in SOQL

I am surprised to see below results.

select id, createddate from account order by id
And below code prints a>b

String a = '0014K000002axOZQAY';
String b = '0014K000002axOaQAI';
if(a>b){
    System.debug('a>b');
} else {
    system.debug('b>a');
}

So why 'order by Id asc' is not doing what it is asked to do? On what basis it is ordering Id fields.

PS 1: Created date looks the same but these accounts are created in the same transaction in order so it looks like the query is following the insertion order while I gave "order by Id asc".

PS 2: I read How to query records by insertion order in SOQL? and I hear that we should not rely on order by Id because Ids are in random order, I get that. Still, it doesn't answer why "order by Id asc" doesn't put Ids in ascending order. Only thing I can think of that I should not consider Id same as String so Id follows some other ordering rules, but what they are?

Best Answer

The ordering is being done appropriately.

The issue is that you're thinking that the Id and String types are equivalent to one another.

If you disregard the last 3 characters of the Id, or change your a and b variables to be the appropriate type (i.e. Id, not String), then you'll see that your test returns the same result as the query

that is, Id a < Id b as the comparison boils down to the ascii value of 'Z' (90) is less than the ascii value of 'a' (97)

Related Topic