function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Cody Drennon 6Cody Drennon 6 

Passing a string into an Order By Soql query

Hello,

I am trying to pass in an order by parameter into my soql query with example below.  I want to be able to order based on the field name that i pass into the parameter.  This is not working though.  Any help would be great. Thanks

 @AuraEnabled
    public static List<Account> getAccounts(string orderby, Integer limits, Integer offsets) {
        
        Integer intlimits = integer.valueOf(limits);
        Integer intoffsets = integer.valueOf(offsets);
        
        
        
        List<Account> accounts = 
            [SELECT Id, Name, Description, CARES_ActiveText__c FROM Account WHERE Type = 'Agency' Order By :orderby LIMIT :intlimits OFFSET :intoffsets];
        //Add isAccessible() check
        return accounts; 
    }
Best Answer chosen by Cody Drennon 6
Karthik KKarthik K
Would this statement fit your needs? List<Account> accountList = Database.query(accountQuery);

I don't think the dynamic variables may bind on the below version.

 List<Account> accounts = 
            [SELECT Id, Name, Description, CARES_ActiveText__c FROM Account WHERE Type = 'Agency' Order By :orderby LIMIT :intlimits OFFSET :intoffsets];

All Answers

Karthik KKarthik K
Can you try using Database.query. Something like below

String accountQuery = 'SELECT Id, Name, Description, CARES_ActiveText__c FROM Account WHERE Type = \''+'Agency'+'\' Order By :orderby LIMIT :intlimits OFFSET :intoffsets';
Database.query(accountQuery);
Cody Drennon 6Cody Drennon 6
@Karthik K
Thanks Karthik.  I need a list of accounts though.  Any way to accompish this using a list?
Karthik KKarthik K
Would this statement fit your needs? List<Account> accountList = Database.query(accountQuery);

I don't think the dynamic variables may bind on the below version.

 List<Account> accounts = 
            [SELECT Id, Name, Description, CARES_ActiveText__c FROM Account WHERE Type = 'Agency' Order By :orderby LIMIT :intlimits OFFSET :intoffsets];
This was selected as the best answer
sfdcMonkey.comsfdcMonkey.com
Hi Cody, please check below post i have done similar work here for pagination using offset in lightning component:
http://sfdcmonkey.com/2017/01/26/display-record-with-pager-buttons-lightning-component/

Hope it will helps you, Kindly let us know if it helps you
Thanks