Ordering Celebs by their most recently updated facts in Sanity.io
This is a classic GROQ challenge! You want to order celebs based on when their related facts were most recently updated. The key is to use a subquery to find each celeb's most recent fact, then sort by that.
Here's the solution from the Stack Overflow thread you posted:
*[_type == "celeb"] {
_id,
name,
"latestFact": *[_type == "fact" && celeb._ref == ^._id] | order(_updatedAt desc)[0]
}
| order(latestFact._updatedAt desc)How this works:
Query all celebs:
*[_type == "celeb"]gets all celebrity documentsProject with subquery: Inside the projection
{}, we create alatestFactfield that runs a nested query:*[_type == "fact" && celeb._ref == ^._id]finds all facts where thecelebreference matches the current celeb's_id(the^operator references the parent document)| order(_updatedAt desc)[0]sorts those facts by most recent first and takes the first one
Sort by the nested field: The outer
| order(latestFact._updatedAt desc)sorts all celebs by their most recent fact's update time
This assumes your fact document has a celeb field that's a reference to a celeb document. If your reference field has a different name, just adjust celeb._ref accordingly.
Performance note: This pattern can be expensive on large datasets since it runs a subquery for each celeb. If you need better performance with many documents, consider denormalizing by storing the latest fact timestamp directly on the celeb document and updating it whenever a fact changes (you could automate this with Sanity Functions).
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.