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.
AI Update

Yes, absolutely! You can use the select() function in GROQ to handle conditional values. This is exactly what you need for your use case.

The select() function works like a switch statement and evaluates conditions in order, returning the first matching value. Here's how you'd solve your specific case:

*[_type == "yourType"] {
  _id,
  "date": select(
    defined(customDate) => customDate,
    _updatedAt
  )
}

This will:

  1. Check if customDate exists and has a value
  2. Return customDate if it's defined
  3. Fall back to _updatedAt if customDate is not set

The defined() function checks whether a field exists and has a non-null value, which is perfect for your scenario. You can also use multiple conditions if needed:

*[_type == "yourType"] {
  _id,
  "date": select(
    defined(customDate) && customDate != "" => customDate,
    defined(publishedDate) => publishedDate,
    _updatedAt
  )
}

This approach ensures your date property always has a value directly in the query, exactly as you wanted. The select() function stops evaluating once it finds the first truthy condition, so it's efficient too.

Show original thread
3 replies
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)
}
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)
}
user M
thank you!

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?