Unlock seamless workflows and faster delivery with our latest releases – get the details

Using conditional statements in Groq queries to add fields with null values

4 replies
Last updated: May 30, 2023
Hi, how can I use something similar to a ternary operator in a groq query?
Basically I want to add two fields together but if one of the fields is null I don't want to add them together
May 30, 2023, 11:03 AM
You can use `select()`:
"foo": select(x != null && y != null => x + y, null)
May 30, 2023, 11:25 AM
At the object level, conditionals allow the same thing instead of a key expression:
* {
  _id,
  _type,
  (x != null && y != null) => {
    "foo": x + y
  }
}
May 30, 2023, 11:26 AM
Thanks, will try this and let you know how it goes
May 30, 2023, 12:27 PM
Thanks worked perfectly!
May 30, 2023, 2:00 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?