πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

Conditional values in GROQ queries

By Saskia Bobinska

Only return a value when a condition is fulfilled

The query

*[
  _type == "article"
  && (
    !defined(image.altText)
    || (
      count(body[_type == 'image' && !defined(altText)]) > 0
    )
  )
] | order(publishedAt desc) {
  _id,
  title,
  // Condition 1 - document level
 !defined(image.altText) => {
    'image': image.asset,
  },
  // Condition 2 - inside portable text
  count(body[_type == 'image' && !defined(altText)]) > 0 => {
    "bodyImage": body[_type == 'image']
  },
}

Let's assume you want to check which images in your documents have an altText set. These image fields are either on the first document level or in the body field (portable text) as a custom block of type image. To get all documents with images without an altText you can use conditional value fetching in your query.

You can setup conditions using this logic in GROQ:

CONDITION => { VALUES_YOU_WANT},

Contributor

Other schemas by author