Structured Content 2022: Join our conference to explore fresh perspectives on content and digital experiences →

Is it possible to have a conditional value within groq?

3 replies
Last updated: Oct 19, 2020

Is it possible to have a conditional value within

groq
?
EX: If a user sets an unique DATE we should use that date instead of
_updatedAt
value?
Would love to do this on the groq side so the
date
property always has a value.

Oct 19, 2020, 3:59 PM

Hi pbj, you could use the

coalesce()
function for this. It takes a number of attribute references and returns the value of the first attribute that is non-null. So if you’d like to default to the
_updatedAt
value if no
date
exists, this should work:
*[_type == 'post']{
  ...,
  'date': coalesce(date, _updatedAt)
}

Oct 19, 2020, 4:21 PM

Hi pbj, you could use the

coalesce()
function for this. It takes a number of attribute references and returns the value of the first attribute that is non-null. So if you’d like to default to the
_updatedAt
value if no
date
exists, this should work:
*[type == 'post']{
  ...,
  'date': coalesce(date, _updatedAt)
}

Oct 19, 2020, 4:21 PM

user M
thank you!

Oct 19, 2020, 4:26 PM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.