Using conditional statements in Groq queries to add fields with null values
GROQ has a couple of great options for handling conditional logic similar to ternary operators, especially when dealing with null values in field addition.
The most straightforward approach is using the select() function, which works like a switch statement or ternary operator:
"foo": select(x != null && y != null => x + y, null)This checks if both x and y are not null, and only then adds them together. Otherwise, it returns null. You can also provide a default value instead of null as the fallback.
For more complex scenarios with multiple conditions, select() supports chaining:
"total": select(
defined(price) && defined(tax) => price + tax,
defined(price) => price,
0
)This uses the defined() function which checks if a property exists and is not null - it's often cleaner than != null checks.
Alternative: Object-level conditionals
You can also use conditionals at the object level instead of the field level:
* {
_id,
_type,
(x != null && y != null) => {
"foo": x + y
}
}This approach only includes the foo field in the result when both values exist, rather than including it with a null value.
Handling null in arithmetic
It's worth noting that in GROQ, if either operand in an addition is null, the entire expression evaluates to null. This is why the conditional check is necessary before performing the addition.
You can also use coalesce() to provide fallback values: coalesce(x, 0) + coalesce(y, 0) would treat null values as zero, though this changes the semantics of your query.
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.