Handling null values when combining address fields in Sanity GROQ query

3 replies
Last updated: Jan 28, 2026
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

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?