Sorting null values in descending order in Groq

2 replies
Last updated: May 30, 2023
Hi all, I have a problem with a sort.
I have a field called search_priority, which is 0, 5 or 10 - or it can be null or undefined.
I do
| order(search_priority desc)
and this doesn’t work as expected.If I eliminate the documents that doesn’t have search_priority set it works fine, but I would like all the documents, just ordered.
Is null interfering somehow? Shouldn’t it be 10, 5, 0, null – or is “null” considered a string, so it becomes null, 10, 5, 0 ?
May 29, 2023, 10:04 PM
Hi Rune. When sorting in descending order,
will appear first. To push the
values to the end of the sort, we can use
to assign a non-
value for the purposes of the sort. The key is to assign a value that will fit into the sort properly.
For numbers,
| order(coalesce(search_priority, -1) desc)
should treat
values as
, putting them “lower” than search_priorities of
and higher. Feel free to change
to a more negative number if there’s any chance that
could be given a negative value in the future. The key is to ensure the
fallback is always the lowest number.
Note that this does not change the
values in any way. It is strictly in the context of the
May 29, 2023, 10:16 PM
Thanks, that worked! Probably a good idea to put that one in the Groq Cheat Sheet 🙂
May 30, 2023, 7:24 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?