Handling null values when combining address fields in Sanity GROQ query

3 replies
Last updated: Feb 23, 2023
How do you handle potential null values that you may want to combine into one property. For example:
  "address": address.line1 + '\\n'
    +address.line2 + '\\n'
    +address.city + ', MA '
    +address.zip,
If address.line2 is null then the whole address returns null. Is there a way to do that part conditionally that there is data in line2?
AI Update

In GROQ, when you concatenate strings with the + operator, if any value is null, the entire result becomes null. To handle this, you can use the coalesce() function, which returns the first non-null value from its arguments.

For your address example, wrap each potentially null field with coalesce() and provide an empty string as the fallback:

"address": coalesce(address.line1, "") + '\n'
  + coalesce(address.line2, "") + '\n'
  + coalesce(address.city, "") + ', MA '
  + coalesce(address.zip, "")

This ensures that even if address.line2 (or any other field) is null, the concatenation still produces a valid string instead of returning null for the entire address.

Bonus tip for cleaner output: If you want to avoid extra newlines when line2 is empty, you can get more sophisticated with conditional logic:

"address": coalesce(address.line1, "") 
  + select(defined(address.line2) => '\n' + address.line2, '')
  + '\n' + coalesce(address.city, "") + ', MA '
  + coalesce(address.zip, "")

Or build it more explicitly with a conditional:

"address": coalesce(address.line1, "") 
  + (defined(address.line2) => ('\n' + address.line2) | '')
  + '\n' + coalesce(address.city, "") + ', MA '
  + coalesce(address.zip, "")

The coalesce() approach is a best practice in GROQ because it moves null-handling logic into your query rather than requiring defensive checks in your frontend code. This makes your application more robust and your data more predictable.

Show original thread
3 replies
You can a combination of
coalesce()
,
select()
, and
array::join()
, etc. Generally I would recommend doing this of string manipulation with JavaScript, though.
Thanks
user L
. I know I'm doing something a little weird. Storytime:I had an old homemade api endpoint that a vendor was using to pull data into a mobile app. We are cutting over to a new software system and website, and I'm trying to coordinate it all. The mobile app vendor didn't have time to make the change to using our sanity api with new data structure, so I'm using groq to reshape the data to look like the old (poorly designed by me) api
🤡
coalesce() is doing the job

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?