Order by date descending with null values last in Sanity
When sorting in descending order using GROQ's order() function, null values appear first by default, which isn't what you want. To push those null values to the end (after the oldest date), you can use the coalesce() function to assign a fallback value specifically for sorting purposes.
Here's how to handle it:
*[_type == "yourType"] | order(coalesce(dateField, "1900-01-01") desc)The coalesce() function returns the first non-null value from its arguments. So when dateField is null, it uses "1900-01-01" (or any date older than your oldest real date) as the sort value. This effectively places null values at the bottom when sorting in descending order.
Important notes:
- The fallback value you choose should be older than any actual date in your dataset to ensure null values come last
- This doesn't modify the actual
dateFieldvalues in your documents—it only affects the sort order - If you're sorting numbers instead of dates, use a very negative number like
-999999as your fallback
For example, if you're sorting blog posts by publish date:
*[_type == "post"] | order(coalesce(publishedAt, "1900-01-01") desc)This will give you posts ordered from newest to oldest, with unpublished posts (where publishedAt is null) appearing at the very end.
Show original thread2 replies
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.