Order by id (ID!) with GraphQL

Let’s say you have this schema:

type Model {
id: ID!
name: String
number: Int
}

using the API explorer I can only order by name and number

How do I ordery by ID!?

1 Like

You don’t need to order by ID as IDs are assigned strictly monotonically increasing (and returned in order). You will need to order if you use a @id directive. In that case standard order: {asc: fieldName} will be applicable

2 Likes

ahhh thanks… appreciate your answer! If the default is returning the IDS in ASC order. Sometimes I would like to query the collection based on the created_time in DESC order. What is the best way to do this? @kaustubh

1 Like
query {
  queryModel {
    id
    name
  }
}
{
  "data": {
    "queryModel": [
      {
        "id": "0x272a",
        "name": "test"
      },
      {
        "id": "0x272b",
        "name": "test1"
      },
      {
        "id": "0x272c",
        "name": "test2"
      },
      {
        "id": "0x272d",
        "name": "test3"
      }
    ]
  }

But I would like the data to come back ORDERD BY DESC ID

{
  "data": {
    "queryModel": [
      {
        "id": "0x272d",
        "name": "test3"
      },
      {
        "id": "0x272c",
        "name": "test2"
      },
      {
        "id": "0x272b",
        "name": "test1"
      },
      {
        "id": "0x272a",
        "name": "test"
      }
    ]
  },
1 Like

It looks like you can’t, as ID! is not listed as an order type.
https://dgraph.io/docs/graphql/queries/order-page/

It looks like by default, it orders by ID ascending, but there doesn’t seem to be a way to order descending by ID!.

While I think this is a good feature request, I also believe you need to ask yourself why you want to order that way. It seems what you really want is to order by createdAt: DateTime in descending order. I would suggest creating this field.

J

FWI: Creating a new field does add complications to your database, but that is not what ID field is made for…, although I am for it.