How to concatenate strings in GROQ and handle null values using coalesce function.
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.
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.