
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeYou can use the select() function in GROQ to handle conditional logic based on whether your array is empty! The select() function works like a switch statement and evaluates conditions in order.
Here's how you can modify your query:
{
"users": select(
count(*[_type=="user" && references(^._id)]) > 0 => *[_type=="user" && references(^._id)] {
// initial data goes here...
_id,
name
},
// fallback data when no users found
*[_type=="fallbackType"][0..10] {
// new data structure here...
_id,
title
}
)
}The key points here:
select() evaluates conditions in order and returns the first matching valuecount() to check if the array has any items: count(*[_type=="user" && references(^._id)]) > 0Alternatively, you can use object-level conditionals if you want to conditionally include the entire field:
{
count(*[_type=="user" && references(^._id)]) > 0 => {
"users": *[_type=="user" && references(^._id)] {
// initial data
}
},
count(*[_type=="user" && references(^._id)]) == 0 => {
"users": *[_type=="fallbackType"] {
// fallback data
}
}
}The select() approach is generally cleaner and more efficient since it stops at the first match rather than evaluating all conditions.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store