How to sort by multiple fields in GraphQL

Wasn't quick to find the official documentation for this, so here it is in case you're wondering.

Single field sorting

sort: {
  order: ASC, 
  fields: frontmatter___season
}Code language: CSS (css)

Multiple field sorting

You can define an array of values for both order an fields.

sort: {
  order: [ASC, ASC], 
  fields: [frontmatter___season, frontmatter___episode]
}Code language: CSS (css)

My full working query for printing a list of TV Shows ordered by season and then by the episode number.

query MyQuery {
  allMarkdownRemark(
    sort: {
      order: [ASC, ASC], 
      fields: [frontmatter___season, frontmatter___episode]
    }
  ) {
    edges {
      node {
        id
        frontmatter {
          title
        }
      }
    }
  }
}

Comments

  1. Bills says:

    Can I create Order_by function manually in the schema?

    1. Hey Bills,

      I’m not that proficient in GraphQL, I don’t seem to get what you’re trying to achieve. A custom order function? I guess the out of the box logic is not enough for your use case?

Leave a Reply

Your email address will not be published. Required fields are marked *