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,
null
will appear first. To push the
null
values to the end of the sort, we can use
coalesce()
to assign a non-
null
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
null
values as
-1
, putting them “lower” than search_priorities of
0
and higher. Feel free to change
-1
to a more negative number if there’s any chance that
search_priority
could be given a negative value in the future. The key is to ensure the
coalesce
fallback is always the lowest number. Note that this does not change the
search_priority
values in any way. It is strictly in the context of the
order()
function.
May 29, 2023, 10:16 PM
R
Thanks, that worked! Probably a good idea to put that one in the Groq Cheat Sheet 🙂