Is it possible to have a conditional value within groq?
groq?
EX: If a user sets an unique DATE we should use that date instead of
_updatedAtvalue?
Would love to do this on the groq side so the
dateproperty always has a value.
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:
- Check if
customDateexists and has a value - Return
customDateif it's defined - Fall back to
_updatedAtifcustomDateis 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 thread3 replies
Was this answer helpful?
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.