GROQ: Get draft version of referenced document if exists, else published

3 replies
Last updated: Jan 28, 2026
Hello all. Need some help in knowing if this is practically allowed in GROQ query.Can I get the draft version of the document (if present, else published) referenced by the parent document with id
xxxx (and not
drafts.xxxx
). So if parent document is referencing
xxxx
, can I show the draft document drafts.xxxx if it exists even though the direct reference of the draft is not added in parent?I tried using match, coalesce but do not seem to get the expected result.

https://groq.dev/jonYis0Kvftcb7RPxZO62V
AI Update

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:

  1. Creating an array with both the draft ID (drafts.xxxx) and published ID (xxxx)
  2. Using score(_id in path("drafts.**")) to assign a higher score to draft documents
  3. 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!

Show original thread
3 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?