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';
} else {

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?

  • The ASCII number for 'A' is 65 and for 'a' is 97. So when we sort these two String, 'A' comes first then 'a'. So when you do order by Id, the Id's which contains capital letters are coming in first as the default order is ascending. Jun 3, 2020 at 15:23

1 Answer 1


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)

  • Then why <<String a = 'Z'; String b = 'a' if(a>b){ System.debug('a>b'); } else { system.debug('b>a'); }>> prints a>b when we know that Z=90 and a=97 are the ascii codes.
    – love gupta
    Jun 3, 2020 at 16:26
  • Answering my above comment, as per developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… "The comparison of two strings is performed according to the locale of the context user and is case-insensitive."
    – love gupta
    Jun 4, 2020 at 1:16

You must log in to answer this question.

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