Order by date descending with null values last in Sanity

2 replies
Last updated: Oct 25, 2021
Is there a way to order a list of items with descending order from a date field, but make the empty fields, with null value, come after the oldest date.
AI Update

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 dateField values in your documents—it only affects the sort order
  • If you're sorting numbers instead of dates, use a very negative number like -999999 as 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 thread
2 replies
I ended up doing it in javascript
[
  ...filteredWork.filter((x) => x.date),
  ...filteredWork.filter((x) => !x.date),
]
Thanks! That looks a lot better

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.

Was this answer helpful?