I am trying to run a query that allows me to sort data inside a table. Depending on the value that gets chosen to sort by I have different queries:

enter image description here

if(selectedField == 'Name'){
         warehouses = [select Id from account where id IN:warehouses order by Name ];
        else if (selectedField == 'Revenue'){
         warehouses = [select Id from account where id IN:warehouses order by AE_letzte_12_Monate__c DESC];
         else {
         warehouses = [select Id from account where id IN:warehouses order by ???];

This works out just fine for fields that are existent on the account. However I want to order by a variable that gets calculated inside the class itself and is not a field on the account:

 public Map<String, String> distances{get;set;}

   for (Account war: warehouses) {

    Location loc1 = Location.newInstance(currentAccount.LocateCity__Latitude__s,currentAccount.LocateCity__Longitude__s);
    Location loc2 = Location.newInstance(war.LocateCity__Latitude__s,war.LocateCity__Longitude__s);

        Integer distance = (Integer) loc1.getDistance(loc2, 'km');
        String km = distance+' km';

        this.distances.put(war.ID, km);

How can I order by this variable? I have read something about dynamic SOQL but I am not quite sure on how that works here. Especially in the combination of different queries / fields and variables.


1 Answer 1


You need to use a field available on an sObject for ORDER BY. Try creating a Custom Sort Order of sObjects.


global class OpportunityWrapper implements Comparable {

   public Opportunity oppy;
   public String calculatedVariable;

   public OpportunityWrapper(Opportunity op, String calVar) {
      oppy = op;
      calculatedVariable = calVar;

   // Compare logic
   global Integer compareTo(Object compareTo) {
       Integer returnValue = 0;

       if(compareTo.field1__c == calculatedVariable) {
          returnValue = 1;
       } else {
          returnValue = -1;
       return returnValue;       

You must log in to answer this question.

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