GROQ Query - Can I Get Draft Version of a Document Referenced by the Parent Document?
This is definitely possible in GROQ! You're asking about the common scenario where a parent document references a published document ID (like xxxx), but you want to show the draft version (drafts.xxxx) if it exists, even though the parent only stores the published reference.
The key technique is to use GROQ's scoring and ordering to prioritize draft documents. Here's the pattern from Sanity's official recipe:
*[_type == 'pokemon' && slug.current == "bulbasaur"]
| score(_id in path("drafts.**"))
| order(_score desc)[0]For your specific case with references, you'd adapt it like this:
*[_id == "parent-doc-id"][0]{
title,
"referencedDoc": *[_id in [
"drafts." + ^.referencedField._ref,
^.referencedField._ref
]] | score(_id in path("drafts.**")) | order(_score desc)[0]
}This works by:
- Creating an array with both the draft ID (
drafts.xxxx) and published ID (xxxx) - Using
score(_id in path("drafts.**"))to assign a higher score to draft documents - Using
order(_score desc)[0]to select the highest-scored document (draft if it exists, otherwise published)
Alternative: Use the previewDrafts perspective
Instead of handling this in your query, you can use Sanity's perspectives feature. When you set perspective=previewDrafts in your API request, Sanity automatically prioritizes drafts over published documents when resolving references:
const query = '*[_id == "parent-doc-id"][0]{ ..., referencedField-> }'
const result = await client.fetch(query, {}, { perspective: 'previewDrafts' })This is the recommended approach for preview/editing environments because it handles all references automatically without complex query logic. The previewDrafts perspective ensures that whenever a draft exists, it takes precedence over the published version - exactly what you're looking for.
For your GROQ playground link, the perspective approach won't work there, but the scoring pattern should solve your issue perfectly!
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.