How to Filter out Null Values using GROQ
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.
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.