Skip to main content
Version: v3.x beta

Sort Query Results

The order_by argument

Results from your query can be sorted by using the order_by argument. The argument can be used to sort nested objects too.

The sort order (ascending vs. descending) is set by specifying the Asc or Desc enum value for the column name in the order_by input object, e.g. {name: Desc}.

By default, for ascending ordering null values are returned at the end of the results and for descending ordering null values are returned at the start of the results.

The order_by argument takes an array of objects to allow sorting by multiple columns.

You can also use nested objects' fields to sort the results. Only columns from object relationships** and **aggregates from array relationships** can be used for sorting.

The following are example queries for different sorting use cases:

Sorting objects

Example: Fetch a list of authors sorted by their names in ascending order:

Sorting nested objects

Example: Fetch a list of authors sorted by their names with a list of their articles that is sorted by their rating:

Sorting by Nested Object Fields

Only columns from object relationships can be used for sorting.

You can sort results based on fields from object relationships, limited to local object relationships between two collections at the moment.

Limitations
  • Sorting is supported only for local relationships (between local collections).
  • Sorting on Array relationships are not supported yet.
  • Sorting based on remote relationships (remote databases or Remote Schema) is not supported yet. :::

For object relationships

For object relationships only columns can be used for sorting.

Example: Fetch a list of articles that are sorted by their author's ids in descending order:

Sorting by multiple fields

As stated above, order_by expects an object with only a single key-value pair. Should you attempt to pass multiple key-value pairs, like in the example below where we're attempting to sort by both lastSeen and then createdAt, you'll receive a validation error like this:

This happens commonly when using the explorer in GraphiQL to select order_by fields. Instead, you can format your query like this wherein an array of objects is passed:

Key order is not preserved

Key order in input object for order_by is not preserved. This means you should only have a single key per object, or you may see unexpected behavior.

Loading...