
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeYou'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:
coalesce() to provide empty string defaultsThe 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.
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.
select() for conditional logicIf 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 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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store