How to efficiently query and group Sanity articles by category?

4 replies
Last updated: Nov 29, 2025
hello there.. i have a main index page which is going to display articles that are written in sanity studio. i want to display articles by category. will i need to call separate queries for each category just to separate the articles out or is there a better way of doing it to avoid 4+ separate queries per page load?
AI Update

Great question! You definitely don't need to make separate queries for each category. There's a much better approach that lets you fetch all articles in a single query and then group them by category on the client side.

The most efficient pattern is to fetch all articles once with their category information, then group them in your application code. Here's how:

*[_type == "article"] {
  _id,
  title,
  slug,
  category->{
    _id,
    title
  }
}

This single query gets all your articles with their category references resolved. Then in your JavaScript/TypeScript code, you can group them:

const articlesByCategory = articles.reduce((acc, article) => {
  const categoryId = article.category._id;
  if (!acc[categoryId]) {
    acc[categoryId] = {
      category: article.category,
      articles: []
    };
  }
  acc[categoryId].articles.push(article);
  return acc;
}, {});

Why this is better:

  1. Single network request - Much faster than 4+ separate queries
  2. Better caching - CDN can cache one response instead of multiple
  3. More efficient - The query engine processes one query plan instead of several

If you have a massive number of articles and need to optimize further, you could add filtering or pagination to the initial query, but for most use cases, fetching all articles and grouping client-side will be the fastest and simplest approach.

The key insight from GROQ query optimization best practices is that moving logic to a single efficient query is almost always better than multiple queries, and client-side grouping is essentially free compared to network overhead.

Show original thread
4 replies

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?