How to order your results in GraphQL
When you retrieve results using GraphQL, the order of the results is not determinable. If you want to get the results in a particular order you can specify a field to sort by along with a sort order (ascending or descending).
Note: Ordering results is particularly important when using paging (see Paging through Results) because there are multiple copies of the underlying database. A query can be routed to any of the underlying copies so there is a possibility that a search for page 1 and a subsequent search for page 2 would be routed to a different underlying database and would return in a different order. Ordering forces the result set into a fixed order regardless of the underlying database copy.
For example, here is a query to retrieve companies which have a GOLD, SILVER or BRONZE Red Flag Alert rating:
query example {
companies(
take:1000
where:{generated_rfa_rating:{in:[GOLD,SILVER,BRONZE]}}
){
items{
company_name
company_number
generated_rfa_rating
incorporation_date
}
}
}
By default the order is indeterminate.
Here is the same query but this time we will sort the results in descending order of the company's incorporation date - so the youngest company will be returned first:
query example {
companies(
take:1000
where:{generated_rfa_rating:{in:[GOLD,SILVER,BRONZE]}}
order:{incorporation_date:DESC}
){
items{
company_name
company_number
generated_rfa_rating
incorporation_date
}
}
}
You can also specify multiple sort fields by specifying an array of orders. When multiple order clauses are specified, then the first in the list is used to sort the entire list, the second order clause orders records within each block of outer results which share the same value for the first field and so on.
For example, here we sort by incorporation date. For each incorporation date we will sort the companies in alphabetical order:
query example {
companies(
take:1000
where:{generated_rfa_rating:{in:[GOLD,SILVER,BRONZE]}}
order:[
{incorporation_date:DESC}
{company_name:ASC}
]
){
items{
company_name
company_number
generated_rfa_rating
incorporation_date
}
}
}
In the result set, we can see that all the companies incorporated on the same date are ordered alphabetically:
{
"company_name":"FARNAC LTD",
"company_number":"14260342",
"generated_rfa_rating":"GOLD",
"incorporation_date":"2022-07-27T00:00:00.000Z"
},
{
"company_name":"KOLESWIFT LTD",
"company_number":"14260386",
"generated_rfa_rating":"GOLD",
"incorporation_date":"2022-07-27T00:00:00.000Z"
},
{
"company_name":"NKEKAM LIMITED",
"company_number":"14259423",
"generated_rfa_rating":"GOLD",
"incorporation_date":"2022-07-27T00:00:00.000Z"
}
If you have any further questions, please reach out to our Support Team via Contact Us.