Sanity Pioneers: Get early access to betas, extra AI credits, and a direct line to the engineering team. Apply now

Order by date descending with null values last in Sanity

2 repliesLast updated: Nov 29, 2025

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:

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

Was this answer helpful?

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.

Related contributions