
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeThis 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 documents
Project with subquery: Inside the projection {}, we create a latestFact field that runs a nested query:
*[_type == "fact" && celeb._ref == ^._id] finds all facts where the celeb reference 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 oneSort 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 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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store