GROQ: Conditional query based on empty array result

3 replies
Last updated: Jan 28, 2026
Hello, Im trying to do a condition inside my groq-query. Anyone that knows how I can check if the array is empty and add other types of data?
Example:

"users" : *[_type=="user" && references(^._id)]  { 
    initial data goes here...
},
users.length === 0 => {
   new data goes here if we could not get any users 
}

AI Update

You 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:

  1. select() evaluates conditions in order and returns the first matching value
  2. Use count() to check if the array has any items: count(*[_type=="user" && references(^._id)]) > 0
  3. The first condition returns your user query with the initial data structure
  4. The fallback (second parameter) returns alternative data when no users are found

Alternatively, 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.

Show original thread
3 replies

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?