I have the below codes to get and run report using Reports API via apex but I need to the sort the first column of the report.

List <Report> reportList = [SELECT Id,DeveloperName FROM Report WHERE Id =: this.report];
MAP<String,String> colMap = new MAP<String,String>(); 
String reportId = (String)reportList.get(0).get('Id');

    // Run a report synchronously
        Reports.ReportResults results = Reports.ReportManager.runReport(reportId,true);
        Reports.ReportMetadata rm = results.getReportMetadata();

        // get report columns
       List<String> reportCols = rm.getDetailColumns();

// sort report column

1 Answer 1


There is a method to set the sort order in reporting metadata in apex

public void setSortColumn(String sortColumn)

Using the below in your code

Id REPORTID = '00O90000001wNWV'; // Query by developer name or store this in custom metadata.
 //WARNING: The Report Id changes between the environments

 // Find the Metadata of the Current Report in Salesforce by describe call
Reports.ReportMetadata reportInputMetadata = 

//Prepare for the sort override
Reports.SortColumn sortcolumn = new Reports.SortColumn();
list<Reports.SortColumn> lstcolumns = new list<Reports.SortColumn>();

// Override with a custom sort

// Run the Report to retrive results
Reports.ReportResults results = 
Reports.ReportManager.runReport(REPORTID,reportInputMetadata, true);
 Reports.ReportMetadata reportOutputMetadata = results.getReportMetadata();
 System.debug('Sort By: ' + reportOutputMetadata.getSortBy());

Reports.ReportFactWithDetails factDetails =
List<Reports.ReportDetailRow> allRows = factDetails.getRows();
System.debug('DATA' + JSON.serializePretty(allRows));
  • Hi Mohith, I saw that too in the documentation but can you please share an example on how to use the method? Nov 4, 2016 at 4:52
  • added example see if that helps .The sortColumn there is a string Nov 4, 2016 at 5:01

You must log in to answer this question.

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