Preface – This post is part of the SAP ABAP OData Tutorial series.
In this article, we will learn how to use $orderby query in our SAP OData services.
Table of Contents
What is the use of $orderby query?
There are many query options to control the amount and order of data. One of the query options provided is $orderby. It adds the sorting capability to OData services. You can order the collection based on the fields available.
SAP NetWeaver Gateway Release 2.0 Support Package >=03
- <fieldname> :is the name of the field.
- <sortorder>: desc/asc
An OData service has retrieved all the Product details, but you want the details in some specified order say, you want the details in descending order by price. Here you can use the $orderby query to achieve the desired output.
You want to fetch the Product details in order by its Price in descending.
In this section, we will implement $orderby on our Product Entity Set.
Step 1: After the creation of the OData service, right Click on Entity Set under Service Implementation, go to ABAP workbench.
Adjust your code for $orderby query. The orderby query option is available in the method by accessing importing parameter IT_ORDER.
In the GetEntitySet method, first, we retrieve all the products and get orderby “fieldname”, “sortorder” and apply them to the BAPI result data to get the required sort order.
Execute the service. If we don’t add $orderby in our service URL, we will get all the results from the system. If we add $order by in-service URL we will get the result based on the sort order provided.
Service URL: /sap/opu/odata/sap/ZDEMO_GW_SRV_SRV/ProductsSet?$orderby=Price asc’.