Joint session with Vercel: How to build intelligent storefronts (May 15th)

Find un-referenced documents with GROQ query

10 repliesLast updated: Nov 29, 2025

Is there a convenient GROQ query to find un-referenced documents?
AI Update

Yes! There's a great GROQ pattern for finding unreferenced documents. The key is to use the references() function in combination with count() to check if any documents reference each document.

Here's the basic pattern:

*[_type == "yourDocType"]{
  _id,
  "refs": count(*[references(^._id)])
}[refs == 0]

This query:

The ^ operator is crucial here - it accesses the parent document's _id from within the subquery, allowing you to check "how many documents reference this document?"

If you just want the IDs of orphaned documents, you can simplify it:

*[_type == "offer"]{
  _id,
  "refs": count(*[references(^._id)])
}[refs == 0]._id

You can also check across multiple document types:

*[_type in ["offer", "product", "page"]]{
  _id,
  _type,
  "refs": count(*[references(^._id)])
}[refs == 0]

Performance tip: This query can be intensive on large datasets since it performs a subquery for each document. Consider running it on specific document types rather than your entire dataset, and maybe during off-peak hours if you have a lot of content.

This is particularly useful for content cleanup, identifying orphaned assets, or finding documents that might be safe to delete since nothing else depends on them. You can find more examples in the backlinks recipe which uses similar reverse reference patterns.

Show original thread
10 replies

Was this answer helpful?

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.

Related contributions