How to sort nested categories alphabetically in GROQ query?

2 replies
Last updated: Nov 10, 2021
Hey! I'm doing a nested query for categories under a blog post and was wondering how i could use groq to sort the returning categories by alphabetical order, or if i need to make some fancy projection... or I'm better off handling it client side.the current query, which returns the posts in the appropriate order:

*[_type == "post"] | order(publishedAt desc, _updatedAt desc) {
    ...,
    categories[] -> {
    "slug": slug.current,
    title
  }
}
I tried to do a projection inside the query but I'm still very new to groq and trying to get the hang of it
AI Update

Good news - you can definitely sort those nested categories right in your GROQ query! You don't need to handle it client-side.

The trick is to use the order() function directly within your projection. Here's how to modify your query:

*[_type == "post"] | order(publishedAt desc, _updatedAt desc) {
    ...,
    "categories": categories[]-> | order(title asc) {
      "slug": slug.current,
      title
    }
}

The key changes:

  1. Wrap the categories projection in quotes to make it an explicit field name ("categories":)
  2. Add | order(title asc) right after the reference resolution (->) but before the projection object
  3. The order() function will sort your categories alphabetically by title

You could also sort by slug if you prefer:

*[_type == "post"] | order(publishedAt desc, _updatedAt desc) {
    ...,
    "categories": categories[]-> | order(slug.current asc) {
      "slug": slug.current,
      title
    }
}

The pattern here is that when you want to order elements within a sub-array, you place the order() function in the pipeline after the dereference operator (->) and before the projection's opening brace.

This is much cleaner than handling it client-side and keeps all your data transformation logic in one place!

Show original thread
2 replies
Hi, sure! Maybe something like:
*[_type == "post"] | order(publishedAt desc, _updatedAt desc) {
  ...,
  "categories": categories[] -> {
    "slug": slug.current,
    title
  } | order(lower(title))
}

πŸ™ thanks that worked!!! I appreciate it

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?