Using coalesce in projection and filtering out null results

2 replies
Last updated: May 22, 2023
Hi, I hope someone might be able to help me with hopefully a relatively straightforward problem.
I'm using coalesce in a projection but also wanted to ensure that it's only included in the returned results if it's not null.


{
"strapline": coalesce(strapLine, strapline),
}

AI Update

You can conditionally include fields in GROQ projections using conditional object attributes! There are a few ways to handle this:

Option 1: Conditional attribute syntax

The cleanest approach is to use a condition before the field definition:

{
  defined(coalesce(strapLine, strapline)) => {
    "strapline": coalesce(strapLine, strapline)
  }
}

This will only include the strapline field in your results when at least one of the source fields has a value. The defined() function checks if a value exists and is not null, which pairs perfectly with coalesce().

Option 2: Using select() function

You can also use the select() function, which works like a switch statement:

{
  "strapline": select(
    defined(strapLine) => strapLine,
    defined(strapline) => strapline
  )
}

With select(), if neither condition matches, the field won't be included in the result at all (or will be null).

Option 3: Shorter conditional syntax

If you want a more compact version:

{
  coalesce(strapLine, strapline) != null => "strapline": coalesce(strapLine, strapline)
}

All three approaches will prevent the field from appearing in your results when both strapLine and strapline are null or undefined. The first option with defined() is generally the most readable and is the recommended pattern for this use case.

Show original thread
2 replies
{
  coalesce(strapLine, strapline) != null => {
    "strapline": coalesce(strapLine, strapline),
  }
}

Thanks Alex!

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?