I want to get records from custom object sort by a field as number. The field I want to sort is string type. Is there any way to do that? I am storing result in list, is there a way to sort list based on the string field but sort it as number?

3 Answers 3


As a workaround you can create a formula field of type Number and define it as:


Then just sort on this formula field instead.

  • I cannot modify add fields in custom object, it belongs to a managed package by someone else.
    – Sanjivani
    May 26, 2014 at 1:30

If the field contains only numbers, then just using ORDER BY in your SOQL should work as you expect. Or, if it must be done after the records are in memory, you could create a wrapper class that implements the Comparable interface and manipulate the fields as necessary.

  • Thanks for giving pointers @AndrewMonshizadeh. I already tried sort by, it does not work as I want. Can you provide some sample on comparable interface? My SOQL query retuns lots of fields.. I was avoiding to have wrapper class, but it looks no choice :(
    – Sanjivani
    May 25, 2014 at 18:17
  • Does your text field actually contain only numbers? Also, according to the documentation there are a few field types where ORDER BY does not apply. May 25, 2014 at 18:36
  • It does only contain numbers.
    – Sanjivani
    May 26, 2014 at 1:29
  • 2
    @Sanjivani here is a link to the documentation on custom sort order. There you will find a complete example of how to implement a custom sort order, along with a test class for that custom sort order. May 26, 2014 at 13:11
  • Thanks @AndrewMonshizadeh, I can use this example next time when I will need to do custom sorting. For the time being I applied some other logic, because the field has values like 1,1.1,2,2.1.1,2.1.2, so they are not numbers. Since I already applied different logic, I will keep your solution bookmarked for next time.
    – Sanjivani
    May 27, 2014 at 2:02

Here is pseudo code of what I have done to sort list by field:

  1. theList=[SOQL query of fields]

  2. loop through the List to create map theMap=key=sortField, value=theList.object

I calculated key as per my requirement for sorting, the valyes in key are like 2.3.4, so i stored it as 2.34 for sorting purpose.

  1. Set keySet = theMap.keySet();

  2. List keyList = new List(); keyList.addAll(keySet);


  3. initialise list again to fill in new sorted entries

    theList=new List();

    //iterate from the first to the last key for (Integer i = 0; i < keyList.size(); i++) { theList.add(i element from map) }

You must log in to answer this question.

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