How to Filter out Null Values using GROQ

3 replies
Last updated: May 24, 2022
๐Ÿ‘‹Can I filter out
NULL
values using groq?
I want to use a query like this:

*[_type == "link"] {
  _id,
  title,
  label
}
But if for instance
label
is empty/null, it should be filtered out from the result, instead of showing up as
label: NULL
.
If I do a query like:

*[_type == "link"] {
  ...
}
I get the intended result (except I now query too many unnecessary fields).
AI Update

Yes, you can filter out null values using GROQ with conditional projections! The syntax uses the arrow operator (=>) to conditionally include fields only when certain conditions are met.

Based on your query, here's how to include the label field only when it's defined:

*[_type == "link"] {
  _id,
  title,
  defined(label) => {
    label
  }
}

The pattern is: CONDITION => { FIELDS_TO_INCLUDE }

The defined() function checks whether a field exists and has a non-null value. When the condition evaluates to true, the fields inside the curly braces are included in the result. If false, those fields are omitted entirely.

Here's a more complex example showing multiple conditional fields:

*[_type == "link"] {
  _id,
  title,
  defined(label) => {
    label
  },
  defined(description) => {
    description
  },
  defined(url) => {
    url
  }
}

This is why your ... spread operator query worksโ€”it automatically excludes null values. But when you explicitly project fields, they're included regardless of their value unless you use conditional projections.

You can also use more complex conditions:

*[_type == "link"] {
  _id,
  title,
  defined(label) && length(label) > 0 => {
    label
  }
}

This checks both that label is defined AND that it's not an empty string.

The conditional projection syntax is particularly useful when working with optional fields, portable text with embedded content, or when you need to handle documents with varying schemas. It gives you fine-grained control over what appears in your query results based on the actual data values.

defined(label) => { label }
Oh, nice ๐Ÿ™‚ !
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?