How to concatenate strings in GROQ and handle null values using coalesce function.

2 replies
Last updated: Aug 15, 2023
Concat string with GROQ

{
 firstName: "A",
 lastName: "B",
 fullName: firstName + lastName
}

// output: fullName: A B 
However, if one of the value is null, the output is null

{
 firstName: NULL,
 lastName: "B",
 fullName: firstName + lastName
}

//output: NULL
Expected: output: B
How should I check the Null value?
AI Update

You're dealing with a common GROQ challenge where null values in string concatenation cause the entire result to become null. There are several good approaches to handle this:

Using coalesce() to provide empty string defaults

The most straightforward solution is to use the coalesce() function to replace null values with empty strings:

{
  firstName: "A",
  lastName: "B",
  fullName: coalesce(firstName, "") + coalesce(lastName, "")
}

This ensures that even if firstName or lastName is null, the concatenation will still work. When firstName is null, it becomes an empty string, so the result would be "B" instead of null.

Using array::join() with array::compact()

Another elegant approach is to use array functions to automatically filter out null values:

{
  firstName: "A",
  lastName: "B",
  fullName: array::join(array::compact([firstName, lastName]), " ")
}

The array::compact() function removes all null values from the array (as shown in the query cheat sheet), and then array::join() concatenates them with a space separator. This is particularly useful when you have multiple fields that might be null.

Using select() for conditional logic

If you need more complex logic, you can use the select() function:

{
  firstName: "A",
  lastName: "B",
  fullName: select(
    defined(firstName) && defined(lastName) => firstName + " " + lastName,
    defined(firstName) => firstName,
    defined(lastName) => lastName,
    ""
  )
}

This gives you fine-grained control over how the concatenation behaves based on which values are present. The defined() function checks whether a property exists and is not null.

The coalesce() approach is usually the simplest and most readable solution for basic null handling in string concatenation! It returns the first non-null value from its arguments, making it perfect for providing fallback values when dealing with potentially null fields.

Perhaps you can try using
coalesce
function ?
coalesce(firstname, lastname)
Maybe try using
coalesce()
function ?
'fullName': coalesce(firstName, "") + coalesce(lastName,"")

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?